10 May 2007

Question: What happens when you call a virtual member from an objects constructor?

by mo


Please consider the following code snippet… (sourced from “Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries”. A definitely good read!)

  public abstract class Base 
  {  
    public Base()
    {  
      Method();  
    }  
    public abstract void Method();  
  }  
     
  public class Derived : Base 
  {  
    private Int32 _value; 
     
    public Derived() : base() 
    { 
      _value = 1; 
    } 
     
    public override void Method()
    { 
      if( 1 == _value )
      { 
        Console.WriteLine( "All is good in the hood!" ); 
      } 
      else
      { 
        Console.WriteLine( "What is wrong?" ); 
      } 
    } 
  }

Can you predict the outcome…?

Hint: When you call a virtual member the most derived override to will be called, even if the constructor of the most derived type has not been fully run yet. Remember… although it’s not explicitly stated in the above sample, when “Derived” is constructed it’s base types constructor is run first!

Perhaps this will make things a little clearer…

  public abstract class Base  
  {  
    public Base()  
    {  
      Method();  
    }  
    public abstract void Method();  
  }  

  public class Derived : Base 
  { 
    private Int32 _value; 

    public Derived() : base() // explicit call to base class constructor
    { 
      _value = 1; 
    } 

    public override void Method() 
    { 
      if ( 1 == _value ) 
      { 
        Console.WriteLine("All is good in the hood!"); 
      } 
      else
      { 
        Console.WriteLine("What is wrong?"); 
      } 
    } 
  }

If this still isn’t clear… maybe now is a good time to put Snippet Compiler to the test. If you don’t already use it, go download it from here…

Then download this source file and run the code…

Default.cs (.88 KB)

csharp