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 :)

Monday, April 24, 2017

C# - Do not call virtual methods in Constructors ( CA2214 )

Calling virtual methods in constructors can create potential problems. See the following sample code

public class BaseClassType
    {
        public BaseClassType()
        {
            DoCall();
        }
        public virtual void DoCall()
        {
            Console.WriteLine("BaseClass DoCall");
        }
    }
    public class DerivedClassType : BaseClassType
    {
        private string type;
        public DerivedClassType()
        {
            type = "Derived";
        }
        public override void DoCall()
        {
            Console.WriteLine("The type is:" + type.ToUpper());
        }
    } 
Create DerivedClassType object in Main()
DerivedClassType derivedObj = new DerivedClassType(); 
Output: NullReferenceException

Execution Flow:
  1. When an object constructed in C#, the initializers run in order from the most derived class to the base class, and then constuctors run in order from the base class to the most derived class. 
  2. When we create the new instance of DerivedClassType, the default parameterless constructor in BaseClassType is called first. i.e. control goes to DoCall() function 
  3. When BaseClassType calls DoCall(), it is virtual method and looks for overridden method . So, it is directed to the DoCall() in DerivedClassTpe. 
  4. However, at this point the code in DerivedClassType constructor has not yet executed, and so the type variable is still referring null. 
  5. When we call type.ToUpper(), It gives null reference exception . I.e. DoCall() method executing before DerivedClassType constructor execution. 
  6. check VS code analysis rule CA2214
 I would recommend convert VS code analysis rule CA2214 from warning to error.

Check another example : 
 public class BadlyConstructedType
    {   protected  string initialized = "No";        
        public BadlyConstructedType()
        {   Console.WriteLine("Calling base ctor.");
            DoSomething();
        }
        public virtual void DoSomething()
        {   Console.WriteLine ("Base DoSomething");
        }
    }    
    public class DerivedType : BadlyConstructedType
    {   public DerivedType ()
        {   Console.WriteLine("Calling derived ctor.");
            initialized = "Yes";
        }
        public override void DoSomething()
        {  Console.WriteLine("Derived DoSomething - initialized ? {0}", initialized);
        }
    }

DerivedType derivedInstance = new DerivedType();

Output :
Calling base ctor.
Derived DoSomething - initialized ? No
Calling derived ctor.

Happy Coding :)

Monday, April 3, 2017

C# 6.0 Features - Shortens and Simplifies the code

C# 6.0 shipped with .NET 4.6 and Visual Studio 2015. VS 2015 comes with brand new Roslyn compiler. Developers can use these features in older version by up grading the compiler.

C# 6.0 features gives grand welcome to the developers to Shortens and Simplifies existing/new code.

See the following new features with examples

1. Null-Conditional operators


This feature concisely and safely access members of an object while still checking for null with the null conditional operator

Before:


Int? userRole = (EmployeeObject != null) ? EmployeeObject.Role : null ;
string deptName= (EmployeeObject != null && EmployeeObject.DeptObject !=null) ? EmployeeObject.DeptObject.DeptName : “”;

After:


Int? userRole = EmployeeObject?.Role ;
string deptName = EmployeeObject?.DeptObject?.DeptName ?? “” ;

2. Auto-Property Initializers

You can assign value to the auto property initializer just like normal field

Before:
 public class Customer
{
   public string First { get; set; };
   public string Last { get; set; };
   public Customer()
   {
      First=”John”;
      Last=”Papa”;
    }
}
After:
 public class Customer
  {
      public string First { get; set; } = "John";
      public string Last { get; set; } = "Papa";
  }

3. Index Initializers 

This feature makes collection initializers more consistent with [] brackets 

     Before:
var numbers = new Dictionary<int, string> {
     { 303,"redirection" },
     { 404, "page not found" },
     { 500, "server error" }
}

After 
var numbers = new Dictionary<int, string> {
           [303] = "redirection",
           [404] = "page not found",
           [500] = "server error"
}
You can download all the features with examples from the link : Download

Happy Coding :)