I've been thinking about how C# properties work and could work.
I know the purpose that C# properties were originally designed for, which is certainly useful. However instead in this question I'm comparing them more abstractly to functions and other programic elements.
Firstly, I wondered, if it were possible, and if so why not, to have a function like C# property.
For example:
byte n = 4;
byte test // property
{
get
{
return n;
}
set
{
n = value;
}
func
{
n++;
}
}
To use as follows:
// n is 4
byte n2 = test; // get
test = 2; // set
// n is now 2
test; // function
// n is now 3
The 'n++' in this example being used only as a simple demonstration.
I also noticed that there is room for more polymorphism than just in function parameter types. For example having overload resolution by return type, get/set and private/public as well.
public test
{
get
{
}
get byte
{
}
private get byte
{
}
get bool
{
}
get myType
{
}
set byte
{
}
set myType
{
}
func
{
}
func(bool)
{
}
func(byte, myType)
{
}
// etc...
}
The above example defines "test" along with reasonably fine detail involving different implementations for using test in various different ways.
More examples:
Read only:
byte test
{
get
{
}
}
Function like:
test
{
func
{
}
}
Function like with parameter polymorphism, returns a byte:
byte test
{
func(bool)
{
}
func(myType, Int16)
{
}
}
Behaves differntly depending on the type assigned to it:
test
{
set bool
{
}
set myType
{
}
}
Function like and could return a value or not, depending on the context it is used:
test
{
byte get
{
}
func(bool)
{
}
func(byte, byte, myType)
{
}
}
The additional possibility for expression and code tidiness should be apparent. However I have been challenged to find specific uses.
One example of how this could be used is equality. Where a bool is expected, for example in an 'if' statement, the behaviour could be defined as being '==', however where there was either nothing to return to, or the return to was other than bool, the behaviour would instead be '='.
if (n.equals(4)) // if n == 4
n.equals(2); // n = 2
Another example is as follows:
class my_list<T>
{
List<T> store;
public count
{
get
{
// unless otherwise apparent,
// use the Int32 version.
return (Int32)count;
}
get byte
{
byte n = 0;
ForEach(var e in store)
n++;
return n;
}
get Int32
{
Int32 n = 0;
ForEach(var e in store)
n++;
return n;
}
private get
{
// An implmentation of "count get" that only
// occurs when count is used from inside the
// my_list class.
}
func
{
print store.Count();
}
set int
{
if (value == 0)
list.Clear();
}
}
}

(). Also check out C#'sFunc<T, TRet>andAction<T>– acidzombie24 Apr 21 '12 at 4:12