Tag Archives: constructor

.NET Order of Initialization

A while back I ran across this article about the dangers of calling a virtual method from the constructor of an inheritable class. The problem comes from the fact that if a new class is derived from the class with the virtual method call in its constructor (and overrides the virtual method), the base class will be calling the derived method on the child class, prior to the child class’ constructor running to completion.

As an extension to the code example to the aforementioned article, I’ve created an example that can a great interview question for understanding the order in which things are initialized. Consider the following set of classes (C#):

public class StringLogger
{
	public static string GetString(string s)
	{
		Console.WriteLine(s);
		return s;
	}
}

public class BaseType
{
	private string baseString 
		= StringLogger.GetString("Base string");
	private static string baseStaticString 
		= StringLogger.GetString("Base static string");

	static BaseType()
	{
		Console.WriteLine("Base static constructor");
	}

	public BaseType()
	{
		Console.WriteLine("Base instance constructor");
		DoSomething();
	}

	public virtual void DoSomething()
	{
		Console.WriteLine("Base DoSomething");
	}
}

public class DerivedType : BaseType
{
	private string derivedString 
		= StringLogger.GetString("Derived string");
	private static string derivedStaticString 
		= StringLogger.GetString("Derived static string");

	static DerivedType()
	{
		Console.WriteLine("Derived static constructor");
	}

	public DerivedType()
	{
		Console.WriteLine("Derived instance constructor");
	}

	public override void DoSomething()
	{
		Console.WriteLine("Derived DoSomething");
	}
}

There is a base class and a derived class, and a utility class that is used to log to the console when one of the string members of one of the other classes is initialized. Now consider creating an instance of the derived class:

public class MainClass
{
	public static void Main()
	{
		Console.WriteLine("Starting...");
		DerivedType d = new DerivedType();
		Console.WriteLine("Done.");
		Console.ReadLine();
	}
}

What will be the output to the console as the DerivedType class is instanciated?

Read more »