Marco Dorantes' WebLog

"Computer science is no more about computers than astronomy is about telescopes" -Edsger W. Dijkstra

Execution order between base and derived inline instance field initializers

Execution order between base and derived inline instance field initializers

  • Comments 1

Talking C#, what is an instance field initializer? Here are two:

class T
{
	private int afield = 1024;
	private StringBuilder anotherfield = new StringBuilder();
}

Now, consider the program below, What would the output be?

class B
{
	public B(int n){Console.WriteLine(n);}
}

class T
{
	public B x=new B(100);
}

class S:T
{
	public B b=new B(200);
}

class exe
{
	static void Main()
	{
		S s=new S();
		Console.WriteLine("Main");
	}
}

Do you think the inline instance field initialization on the base class type T will execute first (in order to its fields be available for use in the derived type)? Using CLR 2.0, the output is:

200
100
Main

What is the reason for such behavior? The answer is the way inline instance field initialization is generated by C# compiler.

It inserts initialization code at the very beginning of the instance constructor and this initialization code gets invoked before the base instance constructor. Be aware.

Now, move instance field initialization to the instance constructor (as you should always do for any class type that matters):

class B
{
	public B(int n){Console.WriteLine(n);}
}

class T
{
	public B x;
	public T()
	{
		x=new B(100);
	}
}

class S:T
{
	public B b;
	public S()
	{
		b=new B(200);
	}
}

class exe
{
	static void Main()
	{
		S s=new S();
		Console.WriteLine("Main");
	}
}

Now the output is:
100
200
Main

In this case the fields in the base class type are fully initialized and available for use in derived class type.

The observed behavior could be part of the reason behind the following:

Note:
A field initializer cannot refer to other instance fields

Leave a Comment
  • Please add 1 and 4 and type the answer here:
  • Post