Search code examples
c#automatic-properties

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


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


Solution

  • 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.