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

 1 public abstract class Base 
 2   {  
 3     public Base()
 4     {  
 5       Method();  
 6     }  
 7     public abstract void Method();  
 8   }  
 9      
10   public class Derived : Base 
11   {  
12     private Int32 _value; 
13      
14     public Derived() : base() 
15     { 
16       _value = 1; 
17     } 
18      
19     public override void Method()
20     { 
21       if( 1 == _value )
22       { 
23         Console.WriteLine( "All is good in the hood!" ); 
24       } 
25       else
26       { 
27         Console.WriteLine( "What is wrong?" ); 
28       } 
29     } 
30   }

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…

 1 public abstract class Base  
 2   {  
 3     public Base()  
 4     {  
 5       Method();  
 6     }  
 7     public abstract void Method();  
 8   }  
 9 
10   public class Derived : Base 
11   { 
12     private Int32 _value; 
13 
14     public Derived() : base() // explicit call to base class constructor
15     { 
16       _value = 1; 
17     } 
18 
19     public override void Method() 
20     { 
21       if ( 1 == _value ) 
22       { 
23         Console.WriteLine("All is good in the hood!"); 
24       } 
25       else
26       { 
27         Console.WriteLine("What is wrong?"); 
28       } 
29     } 
30   }

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)

comments powered by Disqus