In Focus

Why Calling A Virtual Method In Base Class Constructor Is A Bad Practice

In this blog I will try to explain Why calling a virtual method in base class constructor is a bad practice

I will try to explain this concept with a demonstration of calling virtual method in base class constructor

Here is some brief information about the below program
  1. Created a base class "TestBase" and a derived class "TestDerived "
  2. In base class added one property "BaseName" and virtual method "GetName()"
  3. And in base class constructor initialized "BaseName" property and then called GetName() virtual method
  4. In derived class added one property "DerivedName" and overridden "GetName()" method
  5. In derived class constructor initialized "DerivedName" property
  6. And In Main method created object of TestDerived
  1. using System;    
  2. namespace BestPractices    
  3. {    
  4.     static class Program    
  5.     {    
  6.         private static void Main()    
  7.         {    
  8.             TestDerived tb = new TestDerived("John");    
  9.             Console.ReadLine();    
  10.         }    
  11.     }    
  12.     
  13.     public class TestBase     
  14.     {    
  15.         public string BaseName { getset; }    
  16.         public TestBase(string name)    
  17.         {    
  18.             this.BaseName = name;    
  19.             GetName();    
  20.         }    
  21.         public virtual void GetName()    
  22.         {    
  23.             Console.WriteLine("Base GetName called:" + BaseName);    
  24.         }    
  25.     }    
  26.     
  27.     public class TestDerived : TestBase    
  28.     {    
  29.         public string DerivedName { getset; }    
  30.     
  31.         public TestDerived(string name):base(name)    
  32.         {    
  33.             this.DerivedName = name;    
  34.         }    
  35.         public override void GetName()    
  36.         {    
  37.             Console.WriteLine("Derived GetName called:" + DerivedName);    
  38.         }    
  39.     }    
  40. }   
How will the above program execute?
  • In the main method I have created a object of "TestDerived" class which is derived class of "TestBase". As per the constructor execution when we create object of derived class, first the base class constructor will get executed and then derived class constructor. So in our case "TestBase" constructor will get executed first and in TestBase constructor we have initialized BaseName property and then called "GetName()" name method.

  • As per the above point it feels that execution of TestBase constructor is straightforward and GetName method of base class will get executed and it will print output as below:
    Base GetName called::John

    But surprisingly the above output is incorrect and the correct output is:
    Derived GetName called

  • The reason for the above output is, as per the rule of virtual method execution, when we override virtual method in derived class and create derived class object then derived class method will get executed. In the above example we have overridden GetName method in TestDerived class. So when TestBase class constructor calls GetName method, GetName method of derived class(TestDerived) will get executed. GetName method in derived class prints DerivedName, but as Derived class constructor is not executed yet, so DerivedName property will remain uninitialized and it will print the output as "Derived GetName called:"

  • The conclusion of the above demo is that calling a virtual method in base class constructor can cause inconsistent behavior of application, as you are calling derived class method before initializing all the properties of derived class. In our case GetName method of derived class is getting executed before initializing "DerivedName" property
I will try to explain what harm can be caused by calling virtual method in base class constructor

Brief information about the below program
  • Created one base class TestBadPracticeBase, and added one field strBaseList which is List of string and added on virtual method PrintList and inside TestBadPracticeBase constructor initialized strBaseList and called PrintList() virtual method
  • Created one Derived class TestBadPracticeDerived and added one field strList which is List of string. Inside TestBadPracticeDerived  constructor initialized strList. Also overridden base class virtual method PrintList()
  • Inside main method created object of TestBadPracticeDerived class
  1. using System;  
  2. using System.Collections.Generic;  
  3. namespace  TestBadPractices  
  4. {  
  5.     static class Program  
  6.     {  
  7.         private static void Main()  
  8.         {  
  9.             TestBadPracticeDerived tb = new TestBadPracticeDerived();  
  10.             Console.ReadLine();  
  11.         }  
  12.     }  
  13.     public class TestBadPracticeBase  
  14.     {  
  15.         public readonly List<String> strBaseList;  
  16.         public TestBadPracticeBase()  
  17.         {  
  18.             strBaseList = new List<string> { "test1""test2" };  
  19.             PrintList();  
  20.         }  
  21.         public virtual void PrintList()  
  22.         {  
  23.             Console.WriteLine("Base List:");  
  24.             foreach (var item in strBaseList)  
  25.             {  
  26.                 Console.WriteLine(item);  
  27.             }  
  28.         }  
  29.     }  
  30.   
  31.     public class TestBadPracticeDerived : TestBadPracticeBase  
  32.     {  
  33.         public string DerivedName { getset; }  
  34.         public readonly List<String> strList;  
  35.         public TestBadPracticeDerived()  
  36.         {  
  37.             strList = new List<string> { "test1""test2" };  
  38.         }  
  39.         public override void PrintList()  
  40.         {  
  41.             Console.WriteLine("Derived List:");  
  42.             foreach (var item in strList)  
  43.             {  
  44.                 Console.WriteLine(item);  
  45.             }  
  46.         }  
  47.     }  

  48.      
Above program will throw the following exeception:

Unhandled Exception - System.NullReferenceException - Object reference not set to an instance of an object.

Explanation

As explained in the first example, as per the sequence of constructor execution, base class constructor will get executed first. In our case TestBadPracticeBase constructor will get executed first. Inside TestBadPracticeBase constructor we have called virtual method PrintList and as we are creating object of derived class derived class overridden method will get executed so here PrintList method of derived class will get executed. Inside derived class PrintList method we are iterating through strList but strList list is not initialized because derived class constructor is not executed yet. So PrintList method will throw an exception.

Unhandled Exception - System.NullReferenceException - Object reference not set to an instance of an object.

The above two programs prove that calling virtual method inside base class constructor is a bad practice as it can produce inconsistent results.