Should I use public properties and private fields

2019-01-01 13:37发布

In much of the code I have seen (on SO, thecodeproject.com and I tend to do this in my own code), I have seen public properties being created for every single private field that a class contains, even if they are the most basic type of get; set; like:

private int myInt;
public int MyInt 
{
     get { return myInt; }
     set { myInt = value }
}

My question is: how does this differ from:

public int MyInt;

and if we should use properties instead of public fields why should we use them in this specific case? (I am not talking about more complex examples where the getters and setters actually do something special or there is only one get or set (read/write only) rather than just returning/setting a value of a private field). It does not seem to add any extra encapsulation, only give a nice icon in IntelliSense and be placed in a special section in class diagrams!

13条回答
笑指拈花
2楼-- · 2019-01-01 14:23

Actually, if you're using Silverlight, you'll realise that fields cannot be set a static resources and thus you'll have to use a property (even to access a const).

I've realised that when I tried to federate the region names I use in Composite Guidance (PRISM).

However, that's just a language limitations and apart from static/const fields I alsways use properties.

查看更多
登录 后发表回答