Back to all articles

DotNet

`var` vs `dynamic` in C#: What’s the Difference?

Understand the difference between var and dynamic in C#, including compile-time type inference, runtime binding, type safety, and when to use each.

4 min read

0 comments

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 error

The 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

vardynamic
Type inferred at compile timeType/member checks largely happen at runtime
Strongly typedUses dynamic binding
Type cannot change after inferenceVariable can refer to values of different types
Compiler catches invalid member accessSome errors appear only at runtime
Better IntelliSense and compiler safetyLess compile-time safety
Common in normal C# codeUsed 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 running

So even though var and dynamic may look similar, they are very different in terms of type safety and error detection.

Comments

Join the discussion. Please keep comments respectful and relevant.

Loading comments...