#787 – Avoid Public Fields in a Class

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;
            }
        }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #787 – Avoid Public Fields in a Class

  1. Dirk Strauss says:

    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!

Leave a comment