Saturday, September 18, 2010

Control Flow in C#

Hi,
This time I thought to write something about the control flow within a C# program. Control flow is very simple & easy to explain & understand but my idea is to prove it with a running program.
So lets not spend time in reading and writing theory.


Have a look at the following program and try to guess the output:


   class ConcreteClass
{
static int a1 = Init();
static int a2 = 10;
static int a3 = Init();

internal static int Init()
{
return a2;
}

static ConcreteClass()
{
Console.WriteLine("static constructor");
Console.WriteLine(a1);
Console.WriteLine(a2);
Console.WriteLine(a3);
}

internal ConcreteClass()
{
Console.WriteLine("instance constructor");
}
}

class Program
{
public static void Main(string[] args)
{
new ConcreteClass();
}
}

Output:

static constructor

0

10

10

instance constructor


Explanation:

  • CLR executes internal (in-built) field initializers that fills the variables with predefined default values. (zero for int, false for bool, etc ...)
  • Then, Custom field initializers (written by programmer) are executed. e.g. assigning a value or assigning a value by method.
  • Custom field initializers execute in the same order they are written in program.
  • Then, static constructor is executed.
  • Then, instance constructor is executed.
I've not taken two scenarios here
  1. Control Flow in a class hierarchy. (There is no different explanation but try to execute one program and if doubt see this.)
  2. Custom field initializers for instance fields. (Try and check if it works.)
I hope the explanation helps .

Wish you Good Luck.

No comments:

Post a Comment