Thursday, 31 May 2007

Properties in C#

All good programmers have spend hours made getters and setters. So Microsoft have decided to make it a bit harder (I think now, I might change my mind later).

Heres an example of old time code

public class MyClass
private int x;
public int getX()
return x
In you application you can get x with the following code:

Now C# provides a built in mechanism called properties to do the above. In C#, properties are defined using the property declaration syntax. The general form of declaring a property is as follows.

<acces_modifier> <return_type> <property_name>
get { }
set { }

This means that I can do the top example the following way:

Where <access_modifier> can be private, public, protected or internal. The <return_type> can be any valid C# type. Note that the first part of the syntax looks quite similar to a field declaration and second part consists of a get accessor and a set accessor.

For example the above program can be modifies with a property X as follows.

class MyClass
private int x;
public int X // property
{ return x;}
{ x = value;}

The object of the class MyClass can access the property X as follows.

mc.X(10) // setter.
y = mc.X // getter.

I think its a step in a good direction, but splitting the attribute and the property is in my view, just as bad as not having them.

No comments: