What is the difference between VAR and DYNAMIC keywords in C#?


Dynamic

Store any type of value in the dynamic data type variable created using dynamic keyword. Type checking for these types of variables takes place at run-time. Dynamic are dynamically typed variables.

The following is the syntax for declaring a dynamic type −

dynamic <variable_name> = value;

The following is an example −

dynamic val1 = 100;
dynamic val2 = 5;
dynamic val3 = 20;

The dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at runtime.

Var

The "var" keyword initializes variables with var support. Just assign whatever value you want for the variable, integer, string, float, etc. It is a statically typed variable.

Example

 Live Demo

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         var myInt = 5;
         var myString = "Amit";
         Console.WriteLine("Rank: {0} 
Name: {1}",myInt,myString);       }    } }

Output

Rank: 5
Name: Amit

Updated on: 22-Jun-2020

486 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements