Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between public int i and public int i {get; set;} (what is the difference between automatic property and a public member?) [duplicate]

Tags:

c#

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 ?

like image 773
Dani Avatar asked Jan 20 '11 19:01

Dani


People also ask

What is an automatic property?

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.

What is public int?

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.

Why use get set instead of public?

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.


1 Answers

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.

like image 166
Oded Avatar answered Oct 06 '22 00:10

Oded