#310 – Accessibility of Fields in a Class

You can apply access modifiers to fields defined in a class to define their accessibility.  Accessibility dictates what other code is allowed to read and the write the value of a field.

  • public – All code can read/write the field
  • private – Only code in the defining class can read/write the field
  • protected – Code in the defining class or derived classes can read/write the field
  • internal – All code in the defining assembly can read/write the field
  • protected internal – Code in the defining assembly or in derived classes can read/write the field
    public class Dog
    {
        // All code can access
        public string Nickname;

        // Only code in this class can access
        private string genericDogSecretName;

        // Code in this class or subclass can access
        protected int totalBarkCount;

        // Code in same assembly can access
        internal int invokeCount;

        // Code in same assembly or derived classes can access
        protected internal int barkInvokeCount;
    }
Advertisement

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

One Response to #310 – Accessibility of Fields in a Class

  1. Pingback: #787 – Avoid Public Fields in a Class | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: