C# Access Modifiers Are Type Specific, NOT Instance Specific

C# Access Modifiers Are Type Specific, NOT Instance Specific

02/17/2010 10:01:16

Here's an interesting example from a brief discussion I was having on twitter yesterday with @DotNetWill.

Did you realize that access modifiers in .NET are type specific rather than instance specific. It’s not a weird edge case, it is exactly how the language spec lays it out, but it’s not how most people think access modifiers work. This is because it’s not very often that any given type will have a reference to ANOTHER instance of that type, it just tends to not come up.

Either way, could make for some hilariously difficult debugging if you weren’t aware of it and something was “playing with your privates” by reference.

You might have seen this kind of usage in a singlet*on, constructor or builder class (or as @jagregory pointed out, cloning methods), but generally it’s just not a very common usage example. However, it WILL both compile and execute.

// Example of access modifiers being specific to a type not an instance
public class MyType
{
     private MyType _innerMyType;

     public MyType()
     {
     }

     public void MakeInnerMyType()
     {
          _innerMyType = new MyType();
          _innerMyType._innerMyType = new MyType();
     }
}

Nothing ground breaking, but a fun and interesting little example illustrating a common misconception.