Dynamic vs var in C#: Key Differences and Usage
var is used for implicit typing where the type is determined at compile time, while dynamic defers type checking until runtime, allowing more flexible but less safe code. Use var when the type is known and fixed, and dynamic when you need to work with objects whose type is not known until the program runs.Quick Comparison
This table summarizes the main differences between var and dynamic in C#.
| Aspect | var | dynamic |
|---|---|---|
| Type Checking | Compile-time | Runtime |
| Type Inference | Compiler infers type from assigned value | No inference; treated as dynamic type |
| Safety | Type-safe, errors caught at compile time | Not type-safe, errors caught at runtime |
| Use Case | When type is known and fixed | When type is unknown or changes at runtime |
| Performance | Faster due to compile-time binding | Slower due to runtime binding |
| IntelliSense Support | Full support in IDE | Limited support in IDE |
Key Differences
var is a keyword that tells the compiler to infer the variable's type from the value assigned at compile time. Once inferred, the variable has a fixed type and cannot change. This means the compiler checks all operations on the variable for correctness before the program runs, making var type-safe and efficient.
On the other hand, dynamic is a type that bypasses compile-time type checking. Variables declared as dynamic are resolved at runtime, allowing you to call methods or access properties that the compiler does not verify. This flexibility is useful when working with COM objects, dynamic languages, or JSON, but it sacrifices safety and performance.
In summary, var is for implicit but fixed typing known at compile time, while dynamic is for dynamic typing resolved at runtime.
Code Comparison
Here is an example using var to declare a variable with an inferred type.
var number = 10; Console.WriteLine(number + 5);
Dynamic Equivalent
The same example using dynamic allows the variable to hold any type and resolves operations at runtime.
dynamic number = 10; Console.WriteLine(number + 5);
When to Use Which
Choose var when you want the compiler to infer the type and ensure type safety with better performance. It is ideal for most cases where the type is known or obvious.
Choose dynamic when you need flexibility to work with objects whose type is not known until runtime, such as interacting with COM APIs, dynamic JSON data, or scripting languages. Use it sparingly because it can lead to runtime errors and slower code.
Key Takeaways
var infers type at compile time and is type-safe.dynamic defers type checking to runtime and is more flexible but less safe.var for known types and better performance.dynamic for unknown or changing types at runtime.dynamic when type safety and performance are priorities.