Thursday, February 08, 2007

protected, internal, protected internal... are you sure you know them?

the code for this article applies to C#

We all take access modifiers for granted, but can you tell me what protected internal does?

I bet more than half .NET developers will get that wrong, let's review:
  1. private:
    1. This is the least permissive access level.
    2. Accessible only within the body of the class or the struct in which they are declared.
    3. Nested types in the same body can also access those private members
  2. public:
    1. This is the most permissive access level.
    2. There are no restrictions on accessing public members, they are visible anywhere the class is visible
  3. protected:
    1. Access is limited to the containing class or types derived from the containing class.
    2. which means you cannot create an instance of a class and have access to protected members.
  4. internal:
    1. Access is limited to the current assembly.
  5. protected internal:
    1. Access is limited to the current assembly or types derived from the containing class.
that last one is kinda tricky, it kinda "makes sense" that it allows access only in the current assembly and the current or derived classes, but the "or" there is what makes a difference, if you mark a property protected internal, it can actually be accessed outside the assembly. basically protected overrides internal and so I'm not even sure when it makes sense to use such modifier.

If you don't believe me go check it out your self:
Assembly1:
public class Test {
protected internal string prop1;
}

Assembly2://after adding a reference to Assembly 1
public class Test2: Test {
public string prop2;
public Test2() {
prop2 = prop1; //came from the other assembly's class protected internal member
}
}

if this is news for you, you might think, that's stupid, how do you get a property to be visible only the the current assembly, current class and derived classes?

quite simple, you mark your class as internal, so your class can only be accessed from the current assembly, and you mark your property as protected, thus giving access to the derived classes only in the current assembly:

internal class Test {
protected string prop1; //accessible only in this assembly in this class and derived classes
}

1 comment:

Anonymous said...

Thank you so much for your post. It helped me a lot understanding the concept of protected internal.