Using a backing variable for getters and setters

前端 未结 6 1177
北荒
北荒 2020-12-20 13:10

Perhaps this is a silly question, however, I am resonable new to C# (more from a Java background) and have got confused between different examples I have seen regarding gett

6条回答
  •  醉酒成梦
    2020-12-20 13:50

    Referencing automatic properties from within your instance is the same as declaring a public field, which breaks the Encapsulation Principle. Therefore, use automatic properties if you don't access them within the same class. Otherwise, use a member (backing) field and reference that from your local methods while exposing them through a normal .NET property.

    Automatic properties were added with .NET 3.0 as syntactical sugar so you no longer need backing fields that aren't referenced within your class.

提交回复
热议问题