In this article, I will explain you the actual usage of VAR and DYNAMIC type of data. I will provide you the sample examples for both to understand it more clearly. Var was introduced with .NET 3.5 [Visual Studio 2008] and Dynamic was introduced with .NET 4.0 [Visual Studio 2010].

VAR TYPE

Var is a type of declaration which is resolved at compile time that means compiler takes care of the type which is declared as var. The var keyword is used to declare the var type.

Intellisense works for VAR type.
Var type

Var type should be initialized at the time of declaration. If compiler gets any type of error or exception at the time of compilation, it will throw. 


Var Type Declaration

You cannot change the type, if you initialize once.

Var Keyword Erro

In the above example, you saw that compiler treat name as string because it contains only string type of data. Compiler decides it on the time of compilation.

If you try to make changes in the declared var type, it will throw an error at the compile time.

NOTE

You cannot leave the var type as empty or blank; you need to assign some value before compilation.

Dynamic

Dynamic is also a type of declaration which is decided at Run time. It means to say that if you declare a type of variable then compiler will check it on the Rum Time only. The dynamic keyword is used to declare dynamic type.

As you know it will check at rum time, so there is no need to initialize the value at compile time, you can initialize it on run time. 

Intellisense does not work for dynamic type. It does not show the exact type.

Dynamic Keyword

Example

using System;  
namespace ConsoleDemo {  
    public class Program {  
        public static void Main(string[] args) {  
            dynamic name; //will compile and run  
  
            name = "This is C - SharpCorner Article";  
  
            name = 101;  
  
            Console.WriteLine("The value of name is " + name);  
  
  
            Console.ReadLine();  
        }  
    }  
}  

When you run this code, the following will be the output without any error.

Dynamic Type Output

Thanks for reading the article. Hope you enjoyed it.