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)

Featurevardynamic
Type resolutionCompile timeRuntime
Type safetyYesNo
IntelliSenseYesNo
Error checkingCompile timeRuntime
Type change allowedNoYes

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.