开发者

Why some fields are public and some have properties?

Just saw few tutorials and was quite confused that authors sometimes uses both properties with no restrictions and public fields. I cannot see any reason for doing that. Should not I use it just everytime just to be consistent with "standard"?

class A
{
  public bool B;

  pri开发者_如何学Cvate bool c
  public bool C
  {
    get
    {
      return c 
     }
    set
    {
      c=value;
     }

  }
}


Using public fields is almost always a bad idea. Just use properties.

You should also be aware of automatically implemented properties (introduced in C# 3), which allow your C property to be written as:

public bool C { get; set; }


It is always a better practice to have private fields. You should use standard coding guidelines which makes the code consistent.

You can totally eliminate the use of private fields by using the automatic implemented properties.

Public int MyProperty {get; set;}

You can also have private set for the properties so that they can not be set outside the scope of the class, which is like making a read only property

Public int MyProperty {get; private set;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜