When should you use a field rather than a property

2020-02-01 01:36发布

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

Consider:

public string Name;

Or:

private string _Name;
public string Name
{
   get { return _Name; }
   set { _Name = value; }
}

I realize that the second method is more proper and flexible, so that's what I try to use, generally.

But then why do I see people use the first method? Are they just lazy, or is there some specific situation where it's the correct choice? Is it just a matter of preference?

标签: c# theory
7条回答
Summer. ? 凉城
2楼-- · 2020-02-01 02:31

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 <tab> to expedite the laziness in adding a property.

查看更多
登录 后发表回答