Language: EN

csharp-deduccion-tipo-con-var

Type Inference in C#

In modern programming languages, type inference by context is a feature that allows the compiler to infer the type of a variable by 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 where the compiler automatically infers the type of the variable based on the value with which it is initialized.

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();

Use of new() for instantiation

Starting from C# 10.0 we can use the simplified operator new() (instead of using var). In the same way, 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 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