#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);
        }
    }
Advertisements

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

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

%d bloggers like this: