views:

97

answers:

3

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

+11  A: 

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.

Dirk
This is the answer - if you want to change the way Foo is calculated or stored you can do it transparently.
Graphain
I don't understand why you can't transparently change from direct field access to a property. Client code would still use myObject.Foo = bar or Console.Write(myObject.Foo). No changes to client code...
David
@David: Want to bet? a) it's definitely not binary compatible, so you'd *at least* need to recompile. b) It's not source compatible in some situations - for example, you can use a field as an argument for an out parameter, but you can't use a property. Then there's anything using reflection (like data binding). Just say no to public fields...
Jon Skeet
Thanks guys. I read the article linked by 0xA3. Some of the distinctions seem a little obscure (at least for the kind of code I write), but I can see the benefit. Thanks for the clarification.
David
+4  A: 

As always when this topic pops up, read Jon Skeet's

Why Properties Matter

0xA3
A: 

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.

Felix Ungman