#787 – Avoid Public Fields in a Class
February 25, 2013 2 Comments
When you declare a field in a class, you can set its accessibility to: public, private, protected, internal, or protected internal.
In general, you should declare fields as private or protected, instead of making them public. For purposes of encapsulation, you typically expose public data members as properties, rather than fields. This hides the implementation details of the data item from users of the class and makes it easier to change those details without changing or affecting code that uses the class.
Instead of this:
public class Dog { // A field public string Name; }
You should do this:
public class Dog { // A property public string Name { get; set; } }
Or this:
private string name; public string Name { get { return name; } set { // do other stuff name = value; } }
What an excellent series of C# posts. Developers NEED posts such as these to keep us coding fit and to learn new things about C#. Thank you Sean! I’m already a big fan of your blog!
Thanks Dirk!