3

edit : a completely different question than this i'm asking how auto-properties work internally

When i make an automatic Property what happen's in the background ?

This Equals to

public int SomeProperty {get; set;}

This

 private int _someField;
 public int SomeProperty 
 {
    get { return _someField;}
    set { _someField = value;}
 }

Is this what literally happens ( i.e a private field is created ) or is it only presented to just explain things and it works differently

Community
  • 1
  • 1
RazaUsman_k
  • 694
  • 6
  • 20
  • A completely different question why mark it as a duplicate -_- – RazaUsman_k Apr 22 '17 at 15:44
  • 1
    I have reopened the question because the answers on the duplicated question was only mentioning one convertion, i.e the code is equivelant to that but they don't mention that the properties are just methods and get and set methods are generated behind the scenes – Selman Genç Apr 22 '17 at 15:50

1 Answers1

5

Yes, it is exactly what happens, this:

public int SomeProperty {get; set;}

Is a syntactic sugar for this:

private int _someField;
public int SomeProperty 
{
   get { return _someField;}
   set { _someField = value;}
}

And it is a syntactic sugar for:

private int _someField;

public int get_SomeProperty()
{
    return _someField;
}

public void set_SomeProperty(int value)
{
    _someField = value;
} 

You can see the implementation yourself using ildasm.exe:

enter image description here

There are two methods generated to get and set the value of the private field. The only difference is that the name of generated field.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184