Sobes.tech
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 variable's type at compile time. After the type is determined, it becomes fixed and cannot be changed.

// The compiler determines the type 'int' for the variable number
var number = 10;
// number = "hello"; // Compilation error: Cannot convert string to int

dynamic is used to indicate that member resolution (methods, properties, etc.) for the variable will be performed at runtime, not at compile time. This allows using variables whose type is unknown at compile time.

// The type of the variable obj is determined at runtime
dynamic obj = "hello";
// Calling a method that may or may not exist in the string type
var length = obj.Length;

obj = 10;
// Calling a method that may or may not exist in the int type
// var result = obj.Substring(1); // Runtime error, int does not have a Substring method

Comparison:

Characteristic var dynamic
Typing Strict (determined by the compiler) Dynamic (determined at runtime)
Member resolution At compile time (.) At runtime (.)
Error checking At compile time At runtime
Performance High Lower, due to overhead of dynamic resolution
Usage Simplifies syntax when type is obvious Interacting with dynamic APIs, COM, DLR