Why is this:
public string Foo {get;set;}
considered better than this:
public string Foo;
I can't for the life of me work it out.
Thanks
David
Why is this:
public string Foo {get;set;}
considered better than this:
public string Foo;
I can't for the life of me work it out.
Thanks
David
Because you can transparently (from client code's perspective) change the implementation of the setter/getter wheras you cannot do the same, if you expose the underlying property directly (as it would not be binary compatible.)
There is a certain code smell associated with automatic properties, though, in that they make it far to easy to expose some part of your class' state without a second thought. This has befallen Java as well, where in many projects you find get/setXxx
pairs all over the place exposing internal state (often without any need for it, "just in case"), which renders the properties essentially public.
While the purpose of a field is object state storage, the purpose of a property is merely access. The difference may be more conceptual than practical, but automatic properties provides a handy syntax for declaring both.