David
David

Reputation: 16130

Purpose of automatic properties in .NET

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. Can anyone shed some light?

Thanks

Upvotes: 8

Views: 249

Answers (2)

Felix Ungman
Felix Ungman

Reputation: 512

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.

Upvotes: 1

Dirk
Dirk

Reputation: 31061

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.

Upvotes: 12

Related Questions