The var keyword
Learn to declare variables with var where the compiler infers the type.
Type inference with var
In C# the var keyword lets the compiler infer a variable's type from the value on the right. This is called type inference.
Example: var name = "Alex"; makes the compiler treat name as a string. var count = 10; becomes an int.
When you use var you must initialize the variable: var age; alone is a compile error.
If the type is not obvious from the value, an explicit type reads better than var.
When not to use var
var is short and clean but not always the best choice. When the type is hard to guess from the right-hand side, write it out.
Example: var result = Calculate(); leaves result's type unclear. int result = Calculate(); is more readable here.
Watch out for numeric literals too: var x = 5; becomes int, but var x = 5.0; becomes double. If the type is not obvious, avoid var.
Rule of thumb: use var when the type is clear, otherwise be explicit.
Exercise Declare three variables with var and print them
Declare var name with "Alex", var age with 25, and var isActive with true. Print the three variables on separate lines with Console.WriteLine.
Show example solution
First write var name = "Alex"; var age = 25; var isActive = true; then add three Console.WriteLine calls.
Example solution:
var name = "Alex";
var age = 25;
var isActive = true;
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(isActive);
Test yourself
-
Which one causes a compile error?
- var name = "Alex";
- var age;
- var price = 19.99;
- var isActive = true;
Show answer
var age; — Correct! A var declaration must be initialized; var age; is invalid.
-
Keyword for type inference
____ name = "Alex";Show answer
var name = "Alex"; -
Match each declaration to its inferred type
- var name = "Alex";
- string
- var age = 25;
- int
- var price = 19.99;
- double
- var isActive = true;
- bool