Middle
What is the difference between var and dynamic in C#?
sobes.tech AI
Answer from AI
var is used for implicit typing of local variables. The compiler determines the type at compile time.
dynamic is used for working with objects whose type is only known at runtime. Type checking and method calls happen during execution.
| Characteristic | var | dynamic |
|---|---|---|
| Typing | Static (compile-time) | Dynamic (runtime) |
| Type check | During compilation | During execution |
| Performance | High (type is known) | Lower (analysis required at runtime) |
| Restrictions | Only for local variables | For variables, fields, properties, parameters |
| Application | Convenience, code reduction | Interaction with COM, DLR, Reflection |
Example with var:
// Compiler determines that x is of type int
var x = 10;
// Compilation error, as x is defined as int
// x = "hello";
Example with dynamic:
// Type of y is determined at runtime
dynamic y = 10;
// No compilation error, as the check occurs at runtime
y = "hello";
// Calling a method that may not exist; error may occur at runtime
// y.SomeMethod();