Posted on Tuesday October 20, 2009

Abstract methods vs Virtual methods

Many moons ago I was curious about the difference in IL that is produced between abstract and virtual methods, and this is the result.

What IL code is emitted when you have an abstract method, and a virtual method? For the C# below

public abstract class MyAbstract
{
	public abstract void Run(int x);
}

public class MyConcrete
{
	public virtual void Run(int x)
	{
	}
}

The equivalent IL is:

As you can see, MyConcrete.Run() actually contains op codes while MyAbstract.Run() as you’d expect, contains nothing. Abstract methods are virtual though which probably isn’t a huge surprise either. Both of the above use the newslot keyword which indicates that it should override any existing space in the v-table for this method (as they are base classes there is nothing to override).