Thomas Levesque
Thomas Levesque

Reputation: 292445

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 ?

Upvotes: 11

Views: 256

Answers (1)

SLaks
SLaks

Reputation: 887453

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

Upvotes: 8

Related Questions