Nerdy tidbits from my life as a software engineer

Tuesday, April 7, 2009

Overriding / Extending Internal Classes With Reflection.Emit

If you have an internal class:

internal class InternalClass
{
    internal InternalClass()
    {
    }

    protected internal virtual void Test()
    {
    }
}

and you want to override it, the compiler will check to make sure you don’t make the subclasses more accessible than the base class:

public class InternalClassSubclass : InternalClass
{
  // Won't compile!
  // Inconsistent accessibility: base class InternalClass' is less accessible than class 'InternalClassSubclass'
}

But in yet another example of the trickery you can do with Reflection.Emit, you can happily create a subclass of InternalClass and make it public without any problems.  You can also, in fact, override the Test method with a public method and invoke it without any trouble. 

Is this a problem?  I suppose not really.  You can always, for instance, invoke whatever you want using Reflection – so I suppose there’s no harm in being able to do this too.  It certainly makes it a bit easier to generating code since you don’t need to check the visibility of whatever it is you’re overriding.  The only thing you really need to look out for is sealed classes – those you can’t subclass, no matter what.

But it does make you wonder what good visibility checks are if they only happen at compile time.  What good is that if people can come in and invoke whatever they want at runtime?

0 comments: