C# Reference ยท Keywords and Statements
The var keyword
Reference for C# var: implicit typing of local variables, what the compiler infers, where var is not allowed, anonymous types, style advice and common pitfalls.
var declares a local variable whose type the compiler infers from the initializer. It is not dynamic typing: the variable has one fixed, static type from the moment it is declared, exactly as if you had written the type yourself. var x = 5; and int x = 5; compile to the same code.
var shortens declarations with long generic types, and it is the only way to declare a variable of an anonymous type, because such a type has no name you could write.
var names = new Dictionary<string, List<int>>(); var total = 0.0; // double
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
var name = expression; foreach (var item in collection) { } for (var i = 0; i < 10; i++) { } using (var stream = File.OpenRead(path)) { } using var reader = new StreamReader(path); var (x, y) = point; // deconstruction if (obj is Circle { Radius: var r }) { } out var value
| Part | Description |
|---|---|
var |
A contextual keyword. If a type named var is in scope, it takes precedence, so the contextual meaning is lost; avoid naming a type var. |
| Initializer | Required, in the same statement, and must have a type. |
Errors: no initializer is CS0818; initializer null is CS0815; an array with no best common type is CS0826; new() or a collection expression with no target type is CS8754 or CS9176; var on a field is CS0825.
Usage notes
- Where it is allowed. Local variables,
for,foreach,usingandoutdeclarations, deconstruction and patterns. Not allowed for fields, parameters, return types or properties. - Natural types. Since C# 10 lambdas and method groups have a natural type, so
var f = (int x) => x * 2;makesfaFunc<int,int>. The default numeric literal types hold:var n = 1isint,var n = 1Lislong. - Nullability. With nullable reference types enabled,
var s = expr;is treated as nullable (string?) and the compiler tracks whether it may be null from the initializer, so you rarely need to write?yourself. - Readability. Use
varwhen the type is obvious from the right side (var list = new List<int>();,var user = GetUser();with a clear name) or irrelevant. Spell the type out when it carries meaning that the expression hides, such asdecimal price = GetPrice();. - Common pitfalls. The inferred type is the static type of the expression, which may be a base type or interface:
var s = GetShape();is aShape, not theCircleactually returned. Andvar x = 1; x = 2.5;fails becausexisint. - Numbers. An integer literal that does not fit in
intbecomesuint, thenlong, thenulong, but arithmetic onintvalues staysint:var u = int.MaxValue + 1;is rejected at compile time (CS0220), and the same sum with variables wraps around at run time. - Target-typed expressions need a type.
var x = new();andvar y = [1, 2];do not compile (CS8754 and CS9176) because there is no target type; write the type on the left. - Dynamic.
var d = (dynamic)x;gives adynamic;varitself never means dynamic.
Related
- dynamic
- new
- default
- Tutorial: Variables, Type conversion