Tuesday
Oct202009
Abstract methods vs Virtual methods
Tuesday, October 20, 2009 at 10:37PM Many moons I was curious about the difference in IL that is produced between abstract and virtual methods. This post gives the details.
What IL code is emmited when you have an abstract method, and a virtual method? For 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
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).






Reader Comments