In the previous lessons, I’ve said that when declaring a variable, we are required to indicate the compiler the type of the variable and its name. These kind of variables are called explicitly typed variables:
1 |
int integerVariable = 123; // explicitly typed variable |
However, this is not entirely true.
C# version 3.0 introduced the var keyword, which allows programmers to declare local variables without specifying a data type explicitly:
1 2 |
var numericVariable = 100; // implicitly typed local variable, inferred from value as int var otherNumericType = numericVariable + 5; // implicitly typed local variable, inferred from expression as int |
In this case, the compiler will infer the variable’s data type from the value itself or the expression on the right side of the assignment operator. In the above example, var will be compiled as int.
Implicitly typed variables must have a value assigned to them when declared (they must be initialized), or the compiler will generate an error:
1 2 |
var myVariable; // will generate an error, a value must be assigned here! myVariable = 4; |
Unlike explicitly typed variables, we cannot declare multiple implicitly typed variables in the same statement:
1 |
var age = 20, height = 160, weight = 50; // will generate an error |
Implicitly typed variables cannot be used as methods and functions parameters:
1 2 3 4 |
void SomeMethod(var param) // generates an error { } |
Finally, although var can store any kind of variable, this is not the purpose it was built for. Usage of the var keyword should be reserved only when the type of the variable is not known, such as when dealing with anonymous objects, of which we will learn later.
Tags: C# keywords, declaring and initializing variables, var, var variable, variable scope, variable types, variables