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
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.
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.
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.
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#.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With