My Code Logic

Welcome : Guest Login   Register

Build your own logic

Difference between var and dynamic type


      Posted by: Suneel Kumar         22-Aug-2016 01:48 AM         Views: 1028

Introduction :  The keyword 'var' was introduced in C# 3.0 (.NET 3.5 with Visual Studio 2008) and the type 'dynamic' was introduced in C# 4.0 ( .NET 4.0 with Visual Studio 2010). Let us see the difference between these two

 

1) Dynamic can be class label bur Var can't or we can say Dynamic can be global type but Var can be only local type.

class VarDynamic

    {

        public static dynamic a = 5;//No Issue

        public var ab = 5; //Compiler will give error

    

 

2) Dynamic can be method parameter type but Var can't

class VarDynamic

{

    public void AddNumber(dynamic a, dynamic b) // No issue

    {

        int sum = a + b;

    }

    public void AddNumber2(var a, var b) // Compiler Error

    {

        int sum = a + b;   

    }

}

3) Dynamic can be return type of any method but Var can't.

class VarDynamic

{

    public dynamic AddNumber(int a, int b) // No issue

    {

        return a + b;

    }

    public var AddNumber2(int a, int b) // Compiler Error

    {

        return a + b;   

    }

}

4)Dynamic Variable type can be changed during program execution at run time. But Var can't

class VarDynamic

{

    public void method1()

    {

        dynamic v1 = 5;

        v1 = "MyCodeLogic" //v1 type has changed from int to string at runtime

 

        var v2 = 6;

        var v2 = "MyCodeLogic";// v2 type can't changed once at runtime. Compiler Error

    }

}

5) Var should be initialized at the time of declaration but for Dynamic it is not mandatory;

class VarDynamic

{

    public void Method1()

    {

        dynamic v1; // No Error

        var v2;     // Compiler Error(Implicitly-typed local variables must be initialized)

    }

}

6) Var is compile time and Dynamic is run time.

7) Var cannot be Constant but Dynamic can be.

8) Var cannot be Readonly by Dynamic can be.

class VarDynamic

{

    readonly dynamic v3 = 9; // No Error

    public void Method1()

    {

        const dynamic v1 = null; // No Error

        const var v2 = "MyCodeLogic";     // Compiler Error(Implicitly-typed local variables cannot be constant)

        readonly var v3 = 9; // Compiler Error

    }

}

9) Var is type safe, but Dynamic is not.

 

Thanks for reading article . for any query send mail to

admin@mycodelogic.com