I failed to understand why auto implemented property language feature exist in C# 3.0.
What the difference it is making when you say
public string FirstName;
than
public string FirstName { get; set; }
Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.
A field is a variable of any type that is declared directly in a class. A property is a member that provides a flexible mechanism to read, write or compute the value of a private field. A field can be used to explain the characteristics of an object or a class.
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. Instead of writing property like this: public class Dummy.
In C# any "variable" that has a getter and setter is referred to as a property. A variable has no getters and setters or so that is what the text books say. My programming instructor made us have getters and setters for almost every variable that we created in Java.
Because they are implemented differently in the resulting IL code (and machine language). An Automatic property is still exposed as a public getter and setter, whereas a public field is just that - a single field..
Thus, implementing an auto property allows you at some later date to change the internal behavior of either the getter or setter (like adding a validator) without recompiling or re=coding any dependant classes that use it...
Just to add to what other people have said, declaring a public field, the field is accessible for read and write. declaring public automatic property, although the property is public, you can still add modifier to control the accessibility at the get/set level.
public string FirstName { get; private set; }
The user of your class sees FirstName as public property. However, he/she cannot write to it.
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