Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 691
David Avatar asked Aug 02 '10 08:08

David


People also ask

What is an automatic property and how is it useful?

What is automatic property? Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it.

What is use of properties in C# explain auto implemented property with example?

C# 3.0 includes a concept of auto-implemented properties that requires no code inside get and set methods of the class properties. It makes code concise and readable. The C# compiler creates private fields correspond to the properties and are accessible using the get and set methods.

What is the advantage of using properties in C#?

The main advantage of properties is that they allow us to encapsulate our data inside our class in such a way that we can control access to our class's data through only the properties and not by allowing outside programs to access our fields directly.

What is an auto implemented property?

Introduction to C# Auto-Implemented Properties. The properties which do not require any code when used inside the get method and set method of the class are called Auto Implemented Properties in C#.


2 Answers

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.

like image 148
Dirk Avatar answered Oct 30 '22 02:10

Dirk


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.

like image 29
Felix Ungman Avatar answered Oct 30 '22 03:10

Felix Ungman