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. callvirtThis 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
{
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
0 comments:
Post a Comment