I have a code segment:
public class MyClass
{
private string _myProperty;
public string MyProperty
{
get
{
return _myProperty;
}
set
{
_myProperty = value;
}
}
}
What is the point here? I could have declared the _myProperty
string as public and any of my class objects will be able to directly access them and get or set the value.
Instead, we are making _myProperty
private and the using get and set to access them, using the class object.
In either case, the class object is able to access them and the result is always same.
So why use this approach? Is that only because I can implement few constraints in setter?
Apart from that what harm will making member variables public cause? In this example I could expose _myProperty
as public instead of restricting it to this class only by making it private, as OOP would suggest.
No, the result isn't always the same.
Read the article I wrote on this a while ago...
Note that as of C# 2 your code can be a lot shorter though:
public class MyClass
{
public string MyProperty { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With