Language: EN


Type Inference in C#

In modern programming languages, type inference is a feature that allows the compiler to infer the type of a variable in the context in which it is used.

The goal of type inference is to make the code more concise, easier to read, and more maintainable, avoiding unnecessary code repetition.

Inference with var

In C# 3.0, the var keyword was introduced, which is used to declare variables in which the compiler automatically deduces the variable type based on the value with which it is initialized.

The syntax to use 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 assigned initial values.

Type inference even works for complex types, or for types returned by functions.

// all of this also works
var list = new List<string>();
var myObject = MethodThatReturnsSomething();

Using new() for instantiation

Starting from C# 10.0, we can use the new simplified new() operator instead of using var. Similarly, we increase the conciseness of the code.

Person person = new();  // calls the constructor of Person

This approach is similar to the combined use of var, but allows for the explicit declaration of the initialized type, 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 = "John", Age = 30 }; // `person` is an anonymous type