C# Programming/Keywords/var
Appearance
The var
keyword can be used in place of a type when declaring a variable to allow the compiler to infer the type of the variable. This feature can be used to shorten variable declarations, especially when instantiating generic types, and is even necessary with LINQ expressions (since queries may generate very complex types).
The following:
int num = 123;
string str = "asdf";
Dictionary<int, string> dict = new Dictionary<int, string>();
is equivalent to:
var num = 123;
var str = "asdf";
var dict = new Dictionary<int, string>();
var
does not create a "variant" type; the type is simply inferred by the compiler. In situations where the type cannot be inferred, the compiler generates an error:
var str; // no assignment, can't infer type
void Function(var arg1, var arg2) // can't infer type
{
...
}
C# Keywords | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Special C# Identifiers (Contextual Keywords) | |||||||||||||||
| |||||||||||||||
Contextual Keywords (Used in Queries) | |||||||||||||||
|
Note: Var is not a keyword