Skip to content

Smarter type inference with C# 4

Here is a new addition to the C# language in version 4 that doesn’t seem to be getting much attention. The type inference algorithm has become smarter and for the first time we are able to infer generic type arguments from the return types of methods in certain cases.

Consider this example that compiles in C# 4 but does not compile in C# 3:

using System;
using System.Linq;
class Example { static void Main() { var characters = new [] { 97, 98, 99 } .Select(Convert.ToChar); } }

Here I am converting an array of integers to a new sequence of characters. In order to do this I chose to project this new sequence from the old sequence using LINQ’s Enumerable.Select<TSource,TResult> extension method. Now if I were using C# 3 I would have to explicitly provide type arguments for the Select method since the compiler would be unable to infer the types from the usage alone.

Note: This was a follow-up to You don’t always need a lambda expression. As you can see this new functionality gives us many more opportunities to forgo a lambda expression since we are no longer limited to Action delegates.

2 Comments

  1. Andrew,

    I am (favorably) impressed with your blog and your incisive teaching style. And I know that, if I had a clue what you are talking about, I would be even more (favorably) impressed!!!

    Papa

    Posted on 05-Nov-09 at 10:10 am | Permalink
  2. Michael Chandler

    Interesting to know. I’d nearly always assign to an intermediate variable though, so I’ve never come across the C# 3 limitation :)

    Posted on 25-Apr-10 at 4:05 am | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*