C# Automatic Properties

前端 未结 11 1133
有刺的猬
有刺的猬 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:38

    Public data members are evil (in that the object doesn't control modification of it's own state - It becomes a global variable). Breaks encapsulation - a tenet of OOP.

    Automatic properties are there to provide encapsulation and avoid drudgery of writing boiler plate code for simple properties.

    public string ID { get; set;}
    

    You can change automatic properties to non-automatic properties in the future (e.g. you have some validation in a setter for example)... and not break existing clients.

    string m_ID;
    public string ID
    {
       get { return m_ID; }
       set 
       { 
         //validate value conforms to a certain pattern via a regex match
         m_ID = value;
       }
    }
    

    You cannot do the same with public data attributes. Changing a data attribute to a property will force existing clients to recompile before they can interact again.

提交回复
热议问题