When should you use a field rather than a property?

前端 未结 7 1976
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 06:56

Can anyone clearly articulate when you use a field and when to use a property in class design?

Consider:

public string Name;

Or:

7条回答
  •  佛祖请我去吃肉
    2020-12-06 07:07

    Well in C# 3.0 you can actually write:

    public string Name {get; set;}
    

    Which allows you to be proper and lazy.

    Generally speaking, with properties, you get proper encapsulation. You have the choice to allow setting a value, or getting it, or both. Using a public member, you don't have that option.

    It's probably one-part preference, and one-part how your team decides to handle quick and dirty class definitions, but I would say, use properties for get/sets.

    To answer

    Can anyone clearly articulate when you use an attribute and when to use a property in class design?

    You shouldn't ever use a public attribute. You should always use a property instead. It's safer and more flexible. That said, people will be lazy, and just use a public member. However, with C# 3.0 you can use a more terse syntax to define properties, which should satisfy your inner laziness.

    Simply type prop and hit to expedite the laziness in adding a property.

提交回复
热议问题