Possible Duplicate:
When are Getters and Setters Justified
Why do we use get and set method in C#? And why do we use public and private method property?
For example:
public class Date
{
private int month = 7;
public int Month
{
get
{
return month;
}
set
{
if ((value > 0) && (value < 13))
{
month = value;
}
}
}
}
-
1This question is covered in depth here: csharpindepth.com/articles/chapter8/propertiesmatter.aspxRobert Harvey– Robert Harvey2012年07月29日 07:07:40 +00:00Commented Jul 29, 2012 at 7:07
-
1See programmers.stackexchange.com/questions/21802/…, programmers.stackexchange.com/questions/120828/…, programmers.stackexchange.com/questions/38423/… and programmers.stackexchange.com/questions/144347/… among many othersChrisF– ChrisF2012年07月29日 12:16:30 +00:00Commented Jul 29, 2012 at 12:16
-
Those are two questions, not one.tdammers– tdammers2012年07月29日 15:00:14 +00:00Commented Jul 29, 2012 at 15:00
1 Answer 1
Private set modifier
is used to control the access to object's property value.
Public set modifier
is directly accessing the object's property value.
When you have a closed Domain, as a rule of open/close principle, private set modifiers used to restrict direct access to modify the properties of the object.
Private setters were not available before .NET 2.0 Framework. This has meant that people have written separate SetXXX methods if they wanted a public getter but a more limited setter.
public class MyTest
{
string someProperty;
public string SomeProperty
{
get
{
return someProperty;
}
private set
{
someProperty = value;
}
}
}
The basic rules are that you can't specify an access modifier for both the getter and the setter, and you have to use the "extra" modifier to make access more restrictive than the rest of the property.
Your question example comes from MSDN article Using Properties (C# Programming Guide). Look at that again and it will clear up the things.
-
@imonbayazid, please have a look - meta.stackexchange.com/q/5234/187724Yusubov– Yusubov2012年08月03日 14:46:06 +00:00Commented Aug 3, 2012 at 14:46