C# Interview Question #8
What is the difference between var, dynamic, and object?
C# & .NET Fundamentals Junior Beginner
Quick Interview Answer
var uses compile-time type inference. The compiler determines the actual type from the assigned expression, and the variable remains strongly typed.
Detailed Explanation
var uses compile-time type inference. The compiler determines the actual type from the assigned expression, and the variable remains strongly typed.
object is the base type of all .NET types. A value can be stored as object, but type-specific members usually require casting or pattern matching.
dynamic delays member resolution and type checking until runtime. It is flexible but can cause runtime errors that the compiler cannot detect.
Therefore, var is still statically typed, object is a general base type, and dynamic uses runtime binding.
Code Example
var name = "Asif"; // Compile-time type is string
object value = "Hello"; // Stored as object
dynamic data = "Hello"; // Member resolution at runtime
Console.WriteLine(data.Length);