In c# 3.0, the var
keyword has been introduced to declare the implicitly typed local variables without specifying an explicit type. The type of local variables will automatically determine by the compiler based on the right-side value of the initialization statement.
The following two declarations are functionally equivalent in c#.
The above two declarations are functionally equivalent. As discussed, the compiler will automatically infer the type “integer” to the variable x based on the right-side value 50.
Following is the example which will show the various ways of declaring the implicitly typed local variables with var
keyword in c#.
If you observe the above example, we declared and initialized the implicitly typed local variables with different values. The compiler will automatically determine and assign the most appropriate type based on the assigned value.
When we execute the above example, we will get the result as shown below.
In the above example, we used var
keyword to declare the variables at the method level, but we can also use the var
keyword in for, foreach and using statements like as shown below.
In many cases, the use of var is optional, but while working with the anonymous types, we need to declare the variables with var as shown below to access the properties of an object, and it’s a common scenario in LINQ query expressions.
In c#, while creating implicitly-typed local variables, we need to ensure that the variable is declared and initialized in the same statement; otherwise, we will get a compile-time error. The variable cannot be initialized with a null value.
In c#, implicitly-typed variables cannot be used as method parameters and we should not initialize multiple implicitly-typed variables in the same statement.
Same way, we are not allowed to use implicitly-typed variables in initialization expressions like as shown below.
Following are the important points which we need to remember about var
keyword in c#.
var
keyword is useful to declare the implicitly-typed local variables without specifying an explicit type.var
variables must be declared and initialized in the same statement.var
is not allowed to use as a field type at the class level.