Chris's coding blog

Abstract methods vs Virtual methods

October 20, 2009

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:

// MyConcrete
.method public hidebysig newslot virtual instance void Run(int32 x) cil managed
// SIG: 20 01 01 08
{
// Method begins at RVA 0x2133
// Code size 2 (0x2)
.maxstack 8
.language '{3F5162F8-07C6-11D3-9053-00C04FA302A1}', '{994B45C4-E6E9-11D2-903F-00C04FA302A1}', '{5A869D0B-6611-11D3-BD2A-0000F80849BD}'
// Source File 'C:\Examples\Example49\Program.cs'
//000040: {
IL_0000: /* 00 | */ nop
//000041: }
IL_0001: /* 2A | */ ret
} // end of method MyConcrete::Run
// MyAbstract
.method public hidebysig newslot abstract virtual instance void Run(int32 x) cil managed
// SIG: 20 01 01 08
{
// Method begins at RVA 0x0
} // end of method MyAbstract::Run
view raw gistfile1.cs hosted with ❤ by GitHub

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).

csharp

Chris Small

I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via GithubStackoverflowResume