.Net Gotcha – Private Classes With Access To Containing Classes’s Protected Variables (Or Not)

A friend and I were working on some code together when we found an interesting edge case in .Net that neither of us knew about.

This is what we knew: if you have a class with a protected field in it, if you declare a private class inside of that class, the private class can access the protected variable. The example below shows what this looks like.

  public class ParentClassWithProtectedField
    {
        protected readonly int protectedField;

        private class PrivateClassInParentClass
        {
            public void Method(ParentClassWithProtectedField parent)
            {
                Console.WriteLine(parent.protectedField); //Me Work Good!
            }
        }
    }

And this is what we learned: If you create a child class that inherits from the parent class, and declare another Private class in the child class, you cannot access the parent’s protected field from the private class in the child class. I know that was a ton of Parent/Child/Private classes in a short sentence, so here’s an example, building on the previous one, of what won’t work in .NET.

    public class ChildClassOfParentClass : ParentClassWithProtectedField
    {
        private class PrivateClassInChildClass
        {
            public void Method(ParentClassWithProtectedField parent)
            {
                Console.WriteLine(parent.protectedField); // NO WORK!
            }
        }
    }
Advertisements

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 )

Google+ photo

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

Connecting to %s