Tuesday, April 25, 2017

C# - Order of Initialization/Execution in a C# Class

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
  1. Static field initializers
  2. Static constructor
  3. Instance field initializers
  4. Instance constructor
If there is inheritance, the order of initialization becomes
  1. Derived Class static field initializers
  2. Derived Class static constructor
  3. Derived Class instance field initializers
  4. Base Class static field initializers
  5. Base Class static constructor 
  6. Base Class instance field initializers 
  7. Base Class instance constructor 
  8. Derived Class instance constructor
The above sequence cannot hold true in case of Singleton pattern.

See the following example with normal sequence
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
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

Execution Flow: 
  1.  Static field initializer causes the instance constructor to be called before the static constructor. 
  2.  Later Static constructor gets called.
Happy Coding :)

No comments:

Post a Comment