Difference between var and dynamic in C#

Shahzad Aslam
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:

Difference between var and dynamic in C#

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…

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

Responses (1)