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?

svick
  • 214,528
  • 47
  • 357
  • 477
Snake
  • 7,532
  • 5
  • 42
  • 67
  • 1
    They probably improved the type inference capabilities of the compiler, but it doesn't appear to be in the list of changes: http://stackoverflow.com/a/11549260/870604 – ken2k Oct 03 '13 at 12:08

1 Answers1

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

Community
  • 1
  • 1
AlexH
  • 2,582
  • 1
  • 24
  • 33