4

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?

1
  • 1
    They probably improved the type inference capabilities of the compiler, but it doesn't appear to be in the list of changes: stackoverflow.com/a/11549260/870604
    – ken2k
    Commented Oct 3, 2013 at 12:08

1 Answer 1

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.