In modern programming languages, type inference is a feature that allows the compiler to infer the type of a variable from the context in which it is used.
The goal of type inference is to make code more concise, easier to read, and more maintainable, avoiding unnecessary code repetition.
If you want to learn more, check out the Introduction to Programming Course
Inference with var
In C# 3.0 the var keyword was introduced, which is used to declare variables where the compiler automatically deduces the variable’s type based on the value it is initialized with.
The syntax for using var is very simple:
var variableName = initializationExpression;
For example:
var number = 42; // `number` is inferred as `int`
var message = "Hello World"; // `message` is inferred as `string`
In these examples, the C# compiler automatically infers that number is of type int and message is of type string based on the initial values assigned.
Type inference works even for complex types, or for types returned by functions.
// all this also works
var list = new List<string>();
var myObject = MethodThatReturnsSomething();
Using new() for instantiation
Starting from C# 10.0 we can use the simplified new() operator (instead of using var). Similarly, we increase the conciseness of the code.
Person person = new(); // will call the Person constructor
This approach is similar to the combined use of var, but allows for the explicit declaration of the type being initialized, (which is preferred by some programmers).
Practical Examples
Collections and LINQ
The use of var is common in operations with collections and LINQ queries, where types can be long and difficult to write manually.
var integerList = new List<int> { 1, 2, 3, 4, 5 };
var result = integerList.Where(n => n > 2); // `result` is inferred as `IEnumerable<int>`
Anonymous Types
The use of var is mandatory when working with anonymous types, as there is no way to declare the type explicitly.
var person = new { Name = "Luis", Age = 30 }; // `person` is an anonymous type
