Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why generic type inference doesn't work in that case?

When trying to compile the following code in LINQPad :

void Main()
{
    DriveInfo.GetDrives().Select(GetProviderName).Dump();
}

static string GetProviderName(DriveInfo drive)
{
    // some irrelevant WMI code...
}

I get the following error :

The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

If I use a lambda like d => GetProviderName(d) instead of a method group, it works fine... I'm quite surprised, because I was sure the compiler would be able to infer the type from the method group. There is no other GetProviderName method in scope, and the input and output types are clearly defined, so it should be implicitly convertible to a Func<DriveInfo, string>... shouldn't it ?

like image 538
Thomas Levesque Avatar asked May 26 '10 14:05

Thomas Levesque


People also ask

What is infer generic type arguments?

Type inference represents the Java compiler's ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned.

Does Java support type inference?

Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable.

What is type inference in C#?

Type inference is the automatic deduction of the data types of specific expressions in a programming language, usually done at compile time.


1 Answers

This is a limitation in the compiler that was fixed in C# 4.0

like image 166
SLaks Avatar answered Sep 28 '22 19:09

SLaks