var (C# reference)

Beginning with C# 3, variables that are declared at method scope can have an implicit "type" var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // Implicitly typed.
int i = 10; // Explicitly typed.


When var is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable. The compiler's null state analysis protects against dereferencing a potential null value. If the variable is never assigned to an expression that maybe null, the compiler won't emit any warnings. If you assign the variable to an expression that might be null, you must test that it isn't null before dereferencing it to avoid any warnings.

A common use of the var keyword is with constructor invocation expressions. The use of var allows you to not repeat a type name in a variable declaration and object instantiation, as the following example shows:

var xs = new List<int>();

Beginning with C# 9.0, you can use a target-typed new expression as an alternative:

List<int> xs = new();
List<int>? ys = new();

In pattern matching, the var keyword is used in a var pattern.


The following example shows two query expressions. In the first expression, the use of var is permitted but is not required, because the type of the query result can be stated explicitly as an IEnumerable<string>. However, in the second expression, var allows the result to be a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. Use of var eliminates the requirement to create a new class for the result. Note that in Example #2, the foreach iteration variable item must also be implicitly typed.

// Example #1: var is optional when
// the select clause specifies a string
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
                where word[0] == 'g'
                select word;

// Because each element in the sequence is a string,
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)

// Example #2: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
                where cust.City == "Phoenix"
                select new { cust.Name, cust.Phone };

// var must be used because each item
// in the sequence is an anonymous type
foreach (var item in custQuery)
    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);

See also