All About Var And Dynamic Types In CSharp

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

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 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.



You cannot change the type, if you initialize once.



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.



Example

  1. using System;  
  2. namespace ConsoleDemo {  
  3.     public class Program {  
  4.         public static void Main(string[] args) {  
  5.             dynamic name; //will compile and run  
  6.   
  7.             name = "This is C - SharpCorner Article";  
  8.   
  9.             name = 101;  
  10.   
  11.             Console.WriteLine("The value of name is " + name);  
  12.   
  13.   
  14.             Console.ReadLine();  
  15.         }  
  16.     }  
  17. }  
When you run this code, the following will be the output without any error.



Thanks for reading the article. Hope you enjoyed it.

 


Recommended Free Ebook
Similar Articles