var (C#)

var lets the C# compiler infer a variable's type from the value you assign, so you don't have to write the type explicitly. The variable is still strongly typed at compile time.

C#

var is just a convenience — `var x = 5;` is exactly the same as `int x = 5;`. It is most useful with long type names, such as Dictionary<string, List<int>>.

You can only use var when you assign a value on the same line, because the compiler needs something to infer the type from.

Syntax

var name = value;

Examples

C#

var age = 30;
var name = "Ana";
var prices = new List<double>();
Console.WriteLine($"{name} {age}");

Output:

Ana 30

Learn it in a lesson

See also

Back to the Dictionary