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

Using new() for instantiation

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