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 myClassWe can do this in C#:
{
private int myProp;
public void getMyProp() { return myProp; }
public void setMyProp(int newProp) { myProp = newProp; }
}
class myClassThis is a little cleaner and allows us to access the get and set functionality in a very straight forward manner:
{
private int myProp;
pubic int MyProp
{
get { return myProp; }
set { myProp = value; }
}
}
int whee = myClassInstance.myProp;
instead of --> int whee = myClassInstance.getMyProp();
myClassInstance.myProp = 22
instead of --> myClassInstance.setMyProp(22);
- 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.
class myClass
{
public myPublicProp
{
get { return myPublicProp; }
set { myPublicProp = value; }
}
}
MSDN Documentation
2 comments:
Tee hee, pubic
Trust you to find a mistake like that! I'm leaving it in now. I think it should become a C# keyword.
Post a Comment