Friday 4 November 2016

Var Vs Dynamic

Var

1. It is Introduced in C# 3.0

2. It is Statically typed, which means type of variable is decided by the compiler at compile time.

3. We have to initialize at the time of declaration.

Look at the examples below for better understanding

example 1. Var a = "This is Sadiq";

 Looking at assignment of value compiler treats variable a is a type of string.

example 2.  Var a ; 

The above example will throw a compiler error, since the variable is not initialized.

example 3Var a  = 1 ;   //Here it treats a is an integer type

        Var a  = "This is Syed";

It will throw an error, since the compiler has already decided the type of variable a as System.Int32  when the value 1 was assigned to it. Now assigning a string value violates the type safety.

----------------------------------------------------------------------------------------
Dynamic

1. It is Introduced in C# 4.0

2. It is Dynamically typed, which means type of variable is decided by the compiler at run time.

3. We don't need to initialize at the time of declaration.

Look at the example below for better understanding

example 1. dynamic a ;

          a = 1;   // it will work fine and compiles
  
          a = "This is Syed";   // it will work fine and compiles
        


It will compile and run , since the compiler creates the type for variable  a as System.Int32 and then recreates the type as string when the value  "This is Syed" is assigned to it.




Hope this information  helpful to you. Thank you for taking time to look at my blog. ----- Syed Sadiq Ali.      






No comments: