Abstraction isn’t always good for you

I was reminded of the paper by Andrew Kennedy securing the .NET programming model by a conversation the other day about how interfaces are implemented on the CLR.
 
The CLR expects interface methods to be virtual but the C# language doesn’t require this so it effectively virtualises them behind your back.
For example taking the code:
 
    interface IFoo
    {
        void Method1();
    }
    class Program //: IFoo
    {
        public void Method1()
        {   
        }
        static void Main(string[] args)
        {
            MethodInfo method = typeof (Program).GetMethod("Method1");
            Console.WriteLine("IsVirtual " + method.IsVirtual);
        }
    }
 
If we compile and run it we see that Method1 is non-virtual as you’d expect. However, if we uncomment the interface declaration on the class, we see that the method suddenly becomes virtual and final.
 
The IL changes from
 
.method public hidebysig instance void Method1() cil managed
{
    .maxstack 8
    L_0000: ret 
}
to
 
.method public hidebysig newslot virtual final instance void Method1() cil managed
{
    .maxstack 8
    L_0000: ret 
}
It’s often stated that C# is the assembly language of the CLR, but examples like this raise the question about how valid it is to reason about the .NET framework and the CLR using C#.
 
Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

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