Monday 17 July 2017

What is the difference between Var, Dynamic and object in c#


Object
The object class in C# represents the System.Object type, which is the root type in the C# class hierarchy. Generally we use this class when we cannot specify the object type at compile time, which generally happens, when we deal with interoperability.
           object salevalue = 100;

            Console.Write("print object type : " + salevalue.GetType());

            output--- print object type : System.Int32

            salevalue =salevalue + 100 ; // gives complite time error 
Var
The var type was introduced in C# 3.0. It is used for implicitly typed local variables and for anonymous types. The var keyword is generally used with LINQ.

 var amount;   // Initialization of the variable are required at time of declaration.

We cannot change the type of these variables at runtime. If the compiler can’t infer the type, it produces a compilation error.

           var amount1 = 100;
           amount1 = amount1 + 100;
           amount1 = "Hundred";

Dynamic
The dynamic type was introduced in C# 4.0. The dynamic type uses System.Object indirectly but it does not require explicit type casting for any operation at runtime, because it identifies the types at runtime only.

            dynamic amount = 100;
            amount = amount + 100;
            Console.Write("print object type : " + salevalue.GetType());
            amount="Hundred";
             Console.Write("print object type : " + salevalue.GetType());

            output:  print object type : System.Int32
            output:  print object type : System.String

No comments:

Post a Comment