I see this all the time:
private int _myint;
public int MyInt
{
get
{
return _myint;
}
set
{
_myint = value;
}
}
To me this seems identical to:
public int MyInt{ get; set; }
So why does everyone do the former... WHY THE PRIVATE VAR AT ALL?!
An example to expand on what @BFree is saying:
private int _Whatever;
public int Whatever
{
get {return _Whatever;}
set
{
if(value != _Whatever)
{
// It changed do something here...
// maybe fire an event... whatever
}
_Whatever = value;
}
}
First of all, this is new to C# 3.0, it wasn't around before that. Second, if you want to add any custom logic to your getter and setters, you have no choice. So yes, in your example where there's no custom logic, it's the same thing (in fact the compiler generates that for you behind the scenes) but if you want to raise an event for example, or anything like that, you have to be explicit about it.
I'd like to see
public int MyInt{ get; private set; }
more, ;)
but @BFree nailed it
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