What is the best practice for using public fields?

后端 未结 11 1323
旧时难觅i
旧时难觅i 2020-12-03 03:07

When I write a class I always expose private fields through a public property like this:

private int _MyField;
public int MyField
{ get{return _MyField; }
         


        
11条回答
  •  猫巷女王i
    2020-12-03 03:53

    I only ever expose public fields when they're (static) constants - and even then I'd usually use a property.

    By "constant" I mean any readonly, immutable value, not just one which may be expressed as a "const" in C#.

    Even readonly instance variables (like Result and Message) should be encapsulated in a property in my view.

    See this article for more details.

提交回复
热议问题