when the virtual method is overriden in a derived class, this method will be invoked even before the constructor of the derived class has been invoked! which probably was not anticipated by the developer of the derived class!
Example
using System; namespace VirtualTest { public class Base { protected string StrMyString= "Value In Base"; public Base() { Console.WriteLine("Base Class Constructor"); Example1(); } // This will be overridden in the derived type. public virtual void Example1() { Console.WriteLine ("Base DoSomething"); } } public class Derived: Base { public Derived() { Console.WriteLine("Derived Class Constructor"); StrMyString= "Value In Derived"; } public override void Example1() { Console.WriteLine("Derived function is called and Value of StrMyString is {0}", StrMyString); } } public class TestingClass { public static void Main() { Derived d = new Derived (); } } }
Output will be
Base Class Constructor
Derived DoSomething is called - initialized ? Value In Base
Derived Class Constructor
Because this is very contra-intuitive, it is best not to invoke virtual methods from a constructor altogether. Except when the class is sealed of course, because then there can be no derived class.
No comments:
Post a Comment
Your comments, Feedbacks and Suggestions are very much valuable to me :)