Advertisement
Beginner C#, Fundamentals

What is the difference between 'var' and an explicitly typed variable declaration in C#?

Short answer

'var' tells the compiler to INFER the variable's type from the right-hand side expression at COMPILE TIME — the variable is still strongly, statically typed exactly as if you'd written the type explicitly; 'var' is purely a syntax convenience, not a dynamic or loosely-typed…

Save C# mock interview
Advertisement
AModel answer
'var' tells the compiler to INFER the variable's type from the right-hand side expression at COMPILE TIME — the variable is still strongly, statically typed exactly as if you'd written the type explicitly; 'var' is purely a syntax convenience, not a dynamic or loosely-typed declaration.
var count = 5;        // inferred as int, fixed for the variable's lifetime
var name = "Sam";     // inferred as string
// count = "text";    // Error: count is still strictly typed as int
Real-world example
Reducing verbosity for obviously-typed right-hand expressions, like 'var list = new List<string>();'.
Likely follow-ups
  • Can you use 'var' for a field or property declaration, or only for local variables?
Related topics