Initialize Objects Properly: Listing 3: C#, Don't Call Virtual Methods

This sample shows what happens when you call a virtual method from a constructor in a base class. The derived class's constructor hasn't executed, so some of the member variables in the derived class haven't been initialized. That could cause null reference exceptions in many applications.

public class BaseTrackType
{
   private static Marker staticInit = 
     new Marker("base static - initializer1");
   protected static Marker staticInit2 =
     new Marker("base static - initializer2");

   private static Marker staticCtor;

   static BaseTrackType()
   {
     staticCtor = 
       new Marker("base static - ctor");
   }

   private Marker fieldInit = 
     new Marker("base instance - initializer");
   private Marker fieldInit2 =
     new Marker("base instance - initializer2");

   private Marker ctorInit;

   public BaseTrackType()
   {
     ctorInit = new Marker("base instance - ctor");
     // Call a virtual function:
     Console.WriteLine("Contructing an object: " + this.ToString());
   }

   protected Marker CreateMarker(string s)
   {
     return new Marker(s);
   }

   public override string ToString()
   {
     return "A BaseTracktype object";
   }
}

public class DerivedTrackType : BaseTrackType
{
   private static Marker static1Derived = new 	
		  Marker("derived static - initializer");

   private static Marker staticCtorDerived;

   static DerivedTrackType()
   {
     staticCtorDerived = new Marker("derived static - Ctor");
   }

   private Marker derivedInit = new Marker("derived instance - Initializer");

   private Marker derivedCtor;

   public DerivedTrackType()
   {
     derivedCtor = new Marker("derived instance - Ctor");
   }

   public override string ToString()
   {
     StringBuilder rVal = new StringBuilder
       ("A DerivedTrackType object");
     rVal.Append(Environment.NewLine);
     rVal.Append((derivedInit != null) ? 
       "derivedInit has been created" :
       "derivedInit is null");
     rVal.Append(Environment.NewLine);
     rVal.Append((derivedCtor != null) ? 
       "derivedCtor has been created" :
       "derivedCtor is null");
     rVal.Append(Environment.NewLine);
     rVal.Append(base.ToString());
     return rVal.ToString();
   }
}
comments powered by Disqus
Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.