In this article I want to show you how it can be potentially dangerous to call virtual methods in the constructor.
Before going further into the article you can know more about virtual methods here and how virtual methods are called here
Please have a look at the code snippet shown below
public class BaseClass { protected string LocalStr; public BaseClass() { PrintString(); Console.WriteLine(LocalStr.ToUpper()); } public virtual void PrintString() { LocalStr = "Vikram Chaudhary"; } }
If I create an instance of this class and execute the code we will get the desired output as shown below.
static void Main(string[] args) { BaseClass baseInst = new BaseClass();//"VIKRAM CHAUDHARY" as output Console.ReadLine(); }
But the derived class implementer of this class is not aware of this fact that he needs to properly handle the LocalStr variable as it is being called and manipulated after the call to virtual method. Suppose if we have created a derived class as shown below
public class DerivedClass : BaseClass { public override void PrintString() { LocalStr = null; } }
The developer of this class has decided to set the LocalStr variable as null.Now if we create an instance of the derived class as shown below we will get an “Object reference not set to an instance of an object.” exception as while creating an instance of the derived class, the constructor of the base class is called first which in turn calls the overridden version of the PrintString() method which sets the LocalStr variable to null.
Leave a Reply