Glossary / var
var
In C#, var asks the compiler to infer the static type of a local variable from its initializer. It does not make the variable dynamically typed: once inferred, the variable has that compile-time type and normal type checking applies.
Inference rules and use
var count = 3; // int
var names = new List<string>();
var item = GetCustomer(); // exact return type
A var local must have an initializer from which the compiler can infer a type; it cannot be initialized to null alone because no target type is available. var is allowed for local variables and certain loop/resource variables, not fields or method signatures. It is required for anonymous types whose compiler-generated type has no source name. The contextual var pattern in pattern matching is a separate use.
Inference takes the initializer's compile-time type. It does not infer a broader type from later assignments, and the variable cannot change type. var x = null! is technically inferable through the null-forgiving operator but is usually unclear. In nullable-enabled contexts, nullable annotations on inferred reference locals follow compiler inference rules; inspect warnings rather than assuming declaration spelling establishes runtime non-nullness.
Readability guidance
Use var when the right side makes the type obvious, avoids repetition, or names an anonymous type. Prefer explicit types where the inferred type is surprising, overly broad, or important to understanding API intent. Avoid style dogma: consistency and local readability matter more than maximizing or minimizing var.
Interview questions
- Is
vardynamic? No; the type is inferred at compile time and remains fixed. - Can
var x = nullcompile? No, because null alone has no inferable concrete type. - Where is
varrequired? For locals of anonymous types. - Can it be used for fields? No; implicit typing is for local declarations and specified contexts.
- When improve readability? When initializer clearly communicates the type or avoids redundant type repetition.