Difference between var and dynamic in C#
3 min readMay 19, 2024
In C#, both var and dynamic are used for type management, but they serve different purposes and have different behaviors:
1. var
1.1 Data Type Checking:
When we declared a variable with var keword then data type checking is performaed at compile time
Example
// Compiler interpret fruitName as string at compile time
var fruitName = "Mango";
1.2 Data Type Changing
When we declared a variable with var keword then that variable can hold any type of data but we can not change data type of variable during program execution
Example
var fruitDynamic = "Mango";
// This line would cause a compilation error because fruitName was already interpreted as string if we try to chnage it's data type it will give us compilation error
// fruitDynamic = 10;
1.3 Scope:
Variable can only appear inside a local scope with var keyword.
Example
using System;
class Program
{
static void Main(string[] args)
{
// Variable declared inside a block scope
var fruitName = "Orange";
// Accessible within the block scope…