Var vs Dynamic in C#: Key Differences and When to Use Each
var is a compile-time type inference keyword in C# that requires the type to be known at compile time, while dynamic bypasses compile-time type checking and defers it to runtime. Use var for safer, strongly-typed code and dynamic when you need flexibility with unknown types at runtime.Quick Comparison
This table summarizes the main differences between var and dynamic in C#.
| Aspect | var | dynamic |
|---|---|---|
| Type Checking | Compile-time (static) | Runtime (dynamic) |
| Type Inference | Required at compile time | Not required at compile time |
| Safety | Type-safe, errors caught early | No type safety, errors at runtime |
| Use Case | When type is known or obvious | When type is unknown or varies |
| Performance | Faster, no runtime overhead | Slower, runtime binding overhead |
| Example | var x = 5; | dynamic y = GetUnknown(); |
Key Differences
var tells the compiler to infer the variable's type from the assigned value at compile time. Once inferred, the variable behaves like a strongly typed variable, so you get full IntelliSense support and compile-time error checking. You cannot assign a value of a different type later without a cast or error.
dynamic disables compile-time type checking. The compiler treats the variable as if it can hold any type, and all member calls are resolved at runtime. This means you can call methods or access properties that the compiler does not know about, but if they don't exist at runtime, your program will throw exceptions.
In summary, var is safer and preferred when the type is known or can be inferred, while dynamic is useful when working with COM objects, reflection, or data from dynamic sources like JSON where types are not known until runtime.
Code Comparison
Here is how you declare and use var in C# for a simple task:
var number = 10; var text = "Hello"; var sum = number + 5; Console.WriteLine($"Number: {number}, Text: {text}, Sum: {sum}");
Dynamic Equivalent
Here is the equivalent code using dynamic variables:
dynamic number = 10; dynamic text = "Hello"; dynamic sum = number + 5; Console.WriteLine($"Number: {number}, Text: {text}, Sum: {sum}");
When to Use Which
Choose var when: You know the type at compile time and want type safety with better performance and tooling support.
Choose dynamic when: You need to work with types unknown until runtime, such as COM objects, dynamic JSON data, or reflection, and you accept the risk of runtime errors.
In general, prefer var for most cases to keep your code safe and maintainable, and use dynamic only when necessary for flexibility.
Key Takeaways
var infers type at compile time and is type-safe.dynamic defers type checking to runtime and is flexible but risky.var for known types and better performance.dynamic for unknown or changing types at runtime.var for safer, maintainable code unless dynamic behavior is required.