Thursday, April 18, 2024 23:32

Table of contents >> Introduction > Var keyword

Var keyword

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:

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:

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:

Unlike explicitly typed variables, we cannot declare multiple implicitly typed variables in the same statement:

Implicitly typed variables cannot be used as methods and functions parameters:

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: , , , , , ,

Leave a Reply

Follow the white rabbit