Monday, May 26, 2008

[C#] Accessors - get and set cleanliness

While looking at some example code, I bumped into some syntax that looked like a shorthand for declaring get and set methods for a given property - and I thought "well hey, isn't that cool".

Turns out that in C#, this is exactly the case...

"The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both."

Instead of writing something like this which I do all the time:
class myClass
{
private int myProp;
public void getMyProp() { return myProp; }
public void setMyProp(int newProp) { myProp = newProp; }
}
We can do this in C#:
class myClass
{
private int myProp;
pubic int MyProp
{
get { return myProp; }
set { myProp = value; }
}
}
This is a little cleaner and allows us to access the get and set functionality in a very straight forward manner:
  • int whee = myClassInstance.myProp;
    • instead of --> int whee = myClassInstance.getMyProp();
  • myClassInstance.myProp = 22
    • instead of --> myClassInstance.setMyProp(22);
A few things to note:
  • Both the private property, and the public property containing the accessor functions may have very similar names, but do not confuse them.
  • May contain only set [write], only get [read] or both [read/write].
  • The 'value' seen in the set accessor is a C# keyword. It is a free variable that is created by the complier, and no other variables within the set accessor may share that name [duh].
  • There's more to it when talking about inheritance and abstract classes, but perhaps I'll save that for another day.
  • Can also be done for a public member variable, although to me this seems a little silly since you can directly access a public variable anyways. I just added this to show that the syntax was possible.
    class myClass
    {
    public myPublicProp
    {
    get { return myPublicProp; }
    set { myPublicProp = value; }
    }
    }

MSDN Documentation

2 comments:

danly said...

Tee hee, pubic

yamroll said...

Trust you to find a mistake like that! I'm leaving it in now. I think it should become a C# keyword.