20. Type inference#
As we venture deeper into the world of C#, there’s a handy tool we need to discuss: the var
keyword. This allows us to declare a variable without having to explicitly state its type. This is known as “type inference”.
With type inference, the compiler determines the type of the variable at compile-time based on the type of its value. Let’s look at a few examples:
var numberOfMarbles = 5; // int
var label = "Cherries"; // string
var isJarFull = true; // bool
In these lines of code, we’re not explicitly stating the type of each variable. Instead, we’re using the var keyword.
In C#, these variables are called ‘implicitly typed local variables’.
Once the code is compiled, numberOfMarbles
becomes an int
, label
is understood to be a string
, and isJarFull
is a bool
.
The var
keyword can make your code cleaner and easier to read, particularly when dealing with complex types. But remember, the variable must be initialized at the time of declaration when using var
, and the assigned value should not be null
. This is because the compiler needs to infer the type from the assigned value. For example, this will not compile:
var something;
(1,5): error CS0818: Implicitly-typed variables must be initialized
Also, once a value is assigned to a variable declared with var
, the variable’s type cannot be changed. It still has a type, albeit implicitly. If you try to assign a value of a different type later, you’ll receive a compile-time error:
var numberOfMarbles = 5; // int
numberOfMarbles = "Five";
(2,19): error CS0029: Cannot implicitly convert type 'string' to 'int'
Here, because numberOfMarbles
is inferred to be of type int
at the time of its initialization, it cannot then be assigned a string
.
The var
keyword gives you a way to let the compiler do the work of figuring out the types of your variables for you. It’s a powerful tool in your C# toolbox, enabling cleaner and more streamlined code. In the upcoming chapters, we will encounter scenarios where var
proves particularly beneficial in enhancing code readability and maintainability.