Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between var and dynamic in C#
In C#, var and dynamic are two ways to declare variables without explicitly specifying the type. The key difference is when the type is determined − var resolves the type at compile time, while dynamic resolves it at runtime.
var (Implicitly Typed)
var was introduced in C# 3.0. It is a statically typed variable whose data type is inferred by the compiler at compile time based on the value assigned during initialization. A var variable must be initialized at the time of declaration, otherwise the compiler throws an error.
dynamic (Dynamically Typed)
dynamic was introduced in C# 4.0. It is a dynamically typed variable whose type is determined at runtime. A dynamic variable does not need to be initialized at declaration. The compiler skips type checking for dynamic variables, so errors are only caught at runtime.
Example
The following example demonstrates the behavior of var and dynamic ?
using System;
class Program {
static void Main() {
// var: type inferred at compile time
var x = 10; // x is int
var y = "Hello"; // y is string
// var z; // ERROR: must be initialized
Console.WriteLine("var x type: " + x.GetType());
Console.WriteLine("var y type: " + y.GetType());
// dynamic: type resolved at runtime
dynamic a = 10; // a is int at runtime
a = "Now a string"; // OK: type can change
dynamic b; // OK: no initialization needed
b = 3.14;
Console.WriteLine("dynamic a type: " + a.GetType());
Console.WriteLine("dynamic b type: " + b.GetType());
}
}
The output of the above code is ?
var x type: System.Int32 var y type: System.String dynamic a type: System.String dynamic b type: System.Double
Key Differences
| Feature | var | dynamic |
|---|---|---|
| Type Resolution | Compile time | Runtime |
| Introduced In | C# 3.0 | C# 4.0 |
| Initialization Required | Yes (must initialize at declaration) | No (can initialize later) |
| Type Can Change | No (fixed after inference) | Yes (can hold different types) |
| IntelliSense Support | Yes (compiler knows the type) | No (type unknown until runtime) |
| Error Detection | Compile time | Runtime (may throw RuntimeBinderException) |
Conclusion
Use var when you want the compiler to infer the type at compile time while still getting full IntelliSense and type safety. Use dynamic when working with COM objects, reflection, or scenarios where the type is truly unknown until runtime, keeping in mind that errors will only surface at execution time.
