In C#, both var and dynamic let you avoid explicitly writing a variable’s type, but they behave very differently.
The main difference is when C# decides and checks the type.
var — Type is decided at compile time
With var, the compiler figures out the type from the assigned value.
var age = 25;The compiler treats this as:
int age = 25;So age is still strongly typed.
This will work:
var age = 25;
age = 30;But this will not:
var age = 25;
age = "Twenty Five"; // Compile-time errorThe type was inferred as int, so it cannot later become a string.
dynamic — Type checking happens at runtime
With dynamic, C# postpones many type checks until the program is running.
dynamic value = 25;
value = "Hello";
value = true;
value = 10.5;This is allowed because dynamic can refer to values of different types at runtime.
The downside is that some errors are discovered later.
dynamic value = 25;
Console.WriteLine(value.Length);This may compile successfully, but it will fail at runtime because an int does not have a Length property.
var catches mistakes earlier
Example:
var number = 10;
Console.WriteLine(number.Length);The compiler immediately shows an error.
With dynamic:
dynamic number = 10;
Console.WriteLine(number.Length);the error may only appear when that line actually runs.
Quick Comparison
var | dynamic |
|---|---|
| Type inferred at compile time | Type/member checks largely happen at runtime |
| Strongly typed | Uses dynamic binding |
| Type cannot change after inference | Variable can refer to values of different types |
| Compiler catches invalid member access | Some errors appear only at runtime |
| Better IntelliSense and compiler safety | Less compile-time safety |
| Common in normal C# code | Used when runtime flexibility is genuinely needed |
When should you use var?
Use var when the type is obvious from the right-hand side.
var name = "Shreya";
var age = 25;
var price = 99.99m;It keeps code shorter without losing type safety.
When should you use dynamic?
Use dynamic only when the type truly needs to be resolved at runtime, such as certain interoperability or dynamic-object scenarios.
For normal application code, var is usually the safer choice.
Simple way to remember
var → Compiler knows the type before the program runs
dynamic → Type/member checks can happen while the program is runningSo even though var and dynamic may look similar, they are very different in terms of type safety and error detection.