Anemoia
Anemoia

Reputation: 8116

Generic type inference explanation

I have the following piece of code:

namespace ConsoleApplication1
{
    using System.Collections.Generic;
    using System.Linq;

    internal class Program
    {
        private static void Main(string[] args)
        {
            var bar = new object();

            var result = new int[] { 1, 2, 3 }
                .Select/* <int,int> */(bar.Test<int>)
                .ToList();
        }
    }

    public static class Extensions
    {
        public static TReturnType Test<TReturnType>(this object o, int e)
        {
            return default(TReturnType);
        }
    }
}

Compiling this on a machine with only Visual Studio 2012 works like a charm. However to compile it on a machine with just 2010 it is required that you remove the comment around the <int, int>.

Can somebody elaborate on why this now works in 2012, and where in the spec this is explained?

Upvotes: 4

Views: 119

Answers (1)

AlexH
AlexH

Reputation: 2700

The problem comes from type inference of an extension method in VS2010.

If you replace the extension method by a static method, type inference will be ok :

namespace ConsoleApplication1
{
    using System.Collections.Generic;
    using System.Linq;

    internal class Program
    {
        private static void Main(string[] args)
        {
            var result = new int[] { 1, 2, 3 }
                .Select/* <int,int> */(Extensions.Test<int>)
                .ToList();
        }
    }

    public static class Extensions
    {
        public static TReturnType Test<TReturnType>(int e)
        {
            return default(TReturnType);
        }
    }
}

There is no clear answer from Microsoft about this question in C# Language Specification version 5.0 (see section 7.5.2).

For more information, you can read the answers at this similar question : why-doesnt-this-code-compile-in-vs2010-with-net-4-0

Upvotes: 2

Related Questions