0

There are two ways to implement the getter and setter.

A:

public Object Name {get;set;}

B:

private Object _name;
public Object Name
{
       get {return this._name;}
       set {this._name = value;}
}

When we wanner get or set the property we all use

X.Name = "Joy";
String name = X.Name

So I just want to know the difference between them.

Thank you.

greg
  • 1,231
  • 2
  • 14
  • 31
Deo
  • 11
  • 2
  • 2
    [What are Automatic Properties in C# and what is their purpose?](http://stackoverflow.com/questions/6001917/what-are-automatic-properties-in-c-sharp-and-what-is-their-purpose) – user247702 Jun 14 '13 at 09:21
  • 1
    Short answer: there is no difference. You use the first when you can and the second when you must. – Jon Jun 14 '13 at 09:22

2 Answers2

1

The first one is Auto-Implemented Properties which is basically syntactic sugar and results in the same as the second approach.

When using the first auto implemented properties the c# compiler will generate a backing field just like you have it declared in the second case.

If you want to make the property read only you can use declare it like this:

public Object Name {get; private set;}

Community
  • 1
  • 1
Giorgi
  • 28,971
  • 12
  • 82
  • 118
1

They're just the same. The first one is just syntactic sugar.

But if you want to add some logic, say validate the setter value, the second one is what you need.

Jason Li
  • 1,358
  • 10
  • 19