#312 – Accessibility of Methods in a Class

You can apply access modifiers to methods defined in a class to define their accessibility.  Accessibility dictates what other code is allowed to call the method.

  • public – Any code can call the method
  • private – Only code in the defining class can call the method
  • protected – Code in the defining class or derived classes can call the method
  • internal – Any code in the defining assembly can call the method
  • protected internal – Code in the defining assembly or in derived classes can call the method
    public class Dog
    {
        public void BarkALot()
        {
            for (int i = 1; i < 30; i++)
                BarkOnce();
        }

        // Only this class can call
        private void BarkOnce()
        {
            Say("Woof");
        }

        // Subclass can call
        protected void BarkYourName()
        {
            Say(Name);
        }

        // Code in same assembly can call
        internal void DumpBarkCount()
        {
            Say(numBarks);
        }

        // Code in same assembly or subclass can call
        protected internal void BarkNameTwice()
        {
            Say(Name);
            Say(Name);
        }
    }
Advertisement