I’m comming from Java world mainly. So, C# properties do look nice.
I know that with C# 3.0 or above I can use Automatic Properties. I like it even more :).
My question is about a (maybe older) code where I can see this:
private int age;
public int Age {
get { return age; }
set { age = value; }
}
Why do I need the private field age? What I’m I really hiding here?
EDIT:
I completely understand the need for the getter and setter. I mentioned that I’m comming from Java world and doing this all the time.
I do understand that Automatic Properties in C# 3.0 or above are syntatic sugar. But maybe my question has a simpler answer. Does it means that (bellow C# 3.0) the property doesn’t hold any value. So it must get the value from some other field?
Older versions of C# didn’t have automatic properties, so you had to declare your variables that the properties acted upon like in your example. These days, the same code could be expressed as:
I think that answers your question. However, if you are asking “why not just have public int Age; and let programmers set the value on the field directly?”, then:
First thing to keep in mind is that property accessors are compiled into methods. This means that it has a different ABI from just reading/writing to a class member variable, even though it may syntactically look the same as if you had:
So, what this means is that if, at some point down the road, you need to add some notification that the Age field has changed – if you are using properties, you can easily add this notification logic to the property setter without breaking ABI.
If you start off with a public field, then later changing it to a property will change the ABI which is bad for any program(s) that may depend on your assembly. So it’s better to start off with properties.
Hopefully I’m making sense…