class Program
{
static void Main(string[] args)
{
B foo = new B();
foo.DoWork();
Console.ReadLine();
}
}
public class A
{
public virtual void DoWork() { Console.WriteLine("A"); }
}
public class B : A
{
public override void DoWork() { base.DoWork(); Console.WriteLine("B"); }
}
Why don’t I get StackOverflow exception? As I understand it, foo.DoWork() is called, then it calls base.DoWork(), which is virtual and overriden in class B.DoWork() method, which would repeat calling base.DoWork() again until stack is overflown. This overflow is easily achieved when using this instead of base (circular loop of calling self). What does prevent virtual function overriding in this case?
No, when you use
baseit doesn’t make a virtual call. The whole point is to be able to call thebaseimplementation even if you’ve overridden it.If you look in the generated IL, you’ll see it doesn’t use
callvirt:From section 7.6.8 of the C# 5 specification (emphasis mine):