Difference between var & dynamic keyword in C#

Introduction
 
This blog describes the Difference between var & dynamic keyword in C#.
 
var
  • Statically typed - var type of variables are required to be initialized at the time of declaration. Once assigned a value into var type then it act as that data type like int,string,etc. So after that we can't able to change variable datatype.

dynamic

  • Dynamically typed - Dynamically we can change the variable type like int,string,etc. That means the variable type declared at runtime.

Code

  1. using System;  
  2.                       
  3. public class Program  
  4. {  
  5.     public static void Main()  
  6.     {  
  7.         var result1 = 5;  
  8.         //result1 ="Hello World!!"; implicitly convert type 'string' to 'int'  
  9.           
  10.         dynamic result2 = 6;  
  11.           
  12.         result2 = "Welcome to C# Corner";  
  13.           
  14.         Console.WriteLine(result1);// var keyword output  
  15.           
  16.         Console.WriteLine(result2);// dynamic keyword output  
  17.     }  

Output
 
5
Welcome to C# Corner 

Demo : https://dotnetfiddle.net/PHCM3m

Ebook Download
View all
Learn
View all