Possible Duplicates:
c#: why have empty get set properties instead of using a public member variable?
C#: Public Fields versus Automatic Properties
I am using "automatic" properties in my code, and I wonder what is the actual difference between this code:
public class foo{
public int i;
}
and
public class foo{
public int i {get; set;}
}
I know there is a difference, as sine 3rd parties that I've used missed the public members but found them once adding the {get; set;}
.
AS there is no private field behind that, what is going behind the scene ?
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.
Public int is a variable that has no access control. It is effectively a global variable. Unmodified int is a "protected+" int if you will, it operates as a protected int but can't be used by subclasses. Protected ints can be used by subclasses of the class containing that particular int variable.
The main difference between making a field public vs. exposing it through getters/setters is holding control over the property. If you make a field public, it means you provide direct access to the caller. Then, the caller can do anything with your field, either knowingly or unknowingly.
A private field gets generated by the compiler when using automatic properties.
When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
In regards to the difference between the two examples - the first one exposes the field directly for manipulation. This is considered bad practice (think information hiding, loss of encapsulation).
With the second example, you must use the getter and setter and you can add any kind of validation and other logic around these actions.
See this blog post:
If I have a field with no special behavior, should I write a "just in case" property (with trivial get/set), or should I expose a public field?
The reason that the library design guidelines suggest you write a property here is that it is important that libraries be easily versioned. If you put a property in there ahead of time, you can change the property implementation without requiring users to recompile their code.
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