Thursday, February 5, 2026

var vs dynamic

1.var
Type is decided at compile time
Strongly typed
Must be initialized at declaration
IntelliSense & compile-time checking available
Example
var x = 10; // int
var name = "Ram"; // string
👉 If you assign a wrong type later → compile-time error

2.dynamic
Type is decided at runtime
Not strongly typed
No compile-time checking
Errors occur at runtime
Example
dynamic x = 10;
x = "Ram"; // allowed
x.DoSomething(); // runtime error if method not found

3.Key Differences (Interview Points)

Feature

var

dynamic

Type resolution

Compile time

Runtime

Type safety

Yes

No

IntelliSense

Yes

No

Error checking

Compile time

Runtime

Type change allowed

No

Yes


4.When to use?
Use var when type is obvious and you want clean code
Use dynamic when working with:
COM objects
Reflection
JSON / loosely typed data

5.Important interview one-liner
var is statically typed, dynamic is dynamically typed.