C# Automatic Properties

前端 未结 11 1132
有刺的猬
有刺的猬 2020-12-05 03:57

I\'m a bit confused on the point of Automatic properties in C# e.g

public string Forename{ get; set; }

I get that you are saving code by no

11条回答
  •  青春惊慌失措
    2020-12-05 04:28

    I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?

    In the first case, the compiler will automatically add a field for you, and wrap the property. It's basically the equivalent to doing:

    private string forename;
    public string Forename
    {
        get
        { 
            return this.forename;
        }
        set
        {
            this.forename = value;
        }
    }
    

    There are many advantages to using properties over fields. Even if you don't need some of the specific reasons, such as databinding, this helps to future-proof your API.

    The main problem is that, if you make a field, but in v2 of your application, need a property, you'll break the API. By using an automatic property up front, you have the potential to change your API at any time, with no worry about source or binary compatibility issues.

提交回复
热议问题