Are C# properties actually Methods?

前端 未结 4 1204
花落未央
花落未央 2020-12-04 20:54

Till now, I was under the impression that Properties & Methods are two different things in C#. But then I did something like below.

4条回答
  •  伪装坚强ぢ
    2020-12-04 21:33

    Yes, the compiler generates a pair of get and set methods for a property, plus a private backing field for an auto-implemented property.

    public int Age {get; set;}
    

    becomes the equivalent of:

    private int k__BackingField;
    
    public int get_Age()
    {
         return k__BackingField;
    }
    
    public void set_Age(int age)
    {
        k__BackingField = age;
    }
    

    Code that accesses your property will be compiled to call one of these two methods. This is exactly one of the reasons why changing a public field to be a public property is a breaking change.

    See Jon Skeet's Why Properties Matter.

提交回复
热议问题