Compiler Tricks - Inferred Types

The .NET compiler is a terrific thing… After all, it turns your C# into an executable program!

One nice feature of the .NET compiler, which is becoming better each release, is inferred typing. I’d like to lay out a few short examples that might help you develop your programming standards and practices.

Inferring a type when creating an array.

// Create and initialize an array
var myArray = new int[] { 1, 2, 3 };


// Create and initialize an array
var myArray = new [] { 1, 2, 3 };

The compiler knows that your array members are integers, and thus infers the array type as int[].

Inferred types and matching Generic method parameters. Given a Generic method:

/// <summary>
/// A generic method that takes a thing of Type T as input.
/// </summary>
/// <typeparam name="T">The Type.</typeparam>
/// <param name="thing">The thing of Type T.</param>
private void MyGenericMethod<T>(T thing)
    // Do some stuff


// Generic Type Parameters


// Generic Type Parameters

No need to include the Type parameter in the method call because the Generic Type is the same Type as the parameter to the method, so the compiler figures it out.

Inferred types and the var keyword. A pretty classic example.

int myInteger = 3;


var myInteger = 3;

The compiler knows to assign the type of int to myInteger based on the evaluation of the assignment expression. Note that this can be annoying when trying to use interfaces:

var myList = new List<int>();

Assigns var to List<int>, so if you want IList<int> you need to do it the usual way:

IList<int> myList = new List<int>();

A short but sweet post.

See also

comments powered by Disqus