As a C# programmer, knowing C# class order of initialization is very important for avoiding any potential issues.
If you are having C# class - static and instance class constructors, static and instance field initializers. See the following order of execution during initialization
See the following example with normal sequence
Boo
Execution Flow:
If you are having C# class - static and instance class constructors, static and instance field initializers. See the following order of execution during initialization
- Static field initializers
- Static constructor
- Instance field initializers
- Instance constructor
- Derived Class static field initializers
- Derived Class static constructor
- Derived Class instance field initializers
- Base Class static field initializers
- Base Class static constructor
- Base Class instance field initializers
- Base Class instance constructor
- Derived Class instance constructor
The above sequence cannot hold true in case of
Singleton pattern.
public class Foo
{ static Foo()
{
Console.WriteLine("Foo");
}
public Foo()
{
Console.WriteLine("Boo");
}
}
public class Program
{ static void Main()
{
Foo fooObj = new Foo();
}
}
Output:
Foo Boo
See the following example using singleton pattern
Foo
public class Foo
{
private static readonly Foo instance = new Foo();
public static Foo Instance { get { return instance; } }
static Foo()
{
Console.WriteLine("Foo");
}
private Foo()
{
Console.WriteLine("Boo");
}
}
public class Program
{ static void Main()
{
var obj = Foo.Instance;
}
}
Output:
Boo Foo
- Static field initializer causes the instance constructor to be called before the static constructor.
- Later Static constructor gets called.
Happy Coding :)