This is a mirror of official site: http://jasper-net.blogspot.com/

Quirks in .NET Part

| Sunday, February 28, 2010
There are a lot of cool yet strange things in the .NET Framework. A lot of them make you go, “Huh. I didn’t know that.” Let’s take a look at a few of them.

call vs. callvirt

This one is especially interesting to me. In the Microsoft IL specification there are two instructions to call a method, put simply—call and callvirt. call will simply call a method, while callvirt is used to a late-bound method call, meaning that the method which is going to be called is chosen at runtime and not compile time as the simple call would. This is needed for virtual methods when a VTable lookup is required.

Interestingly, all calls to instance classes are compiled as callvirt, even if the method being called is not virtual (thus at compile time we know exactly which method will be called.) I thought it was a bug at first, but really it was a fix for another bug. Consider this code:

class Program
{
   static void Main()
   {
       HelloWorld instance = null;
       instance.SayHello();
   }
}

public class HelloWorld
{
   public void SayHello()
   {
       System.Console.WriteLine("Hello World!");
   }
}

Read more: DevBlog Part 1, Part 2

Posted via email from jasper22's posterous

0 comments: