Mahesha999
Mahesha999

Reputation: 24731

How Linq infers types from Lambda

Here is the original Linq:

       var developersUsingCSharp =
                from d in developers
                    where d.Language == "C#"
                    select d.Name;

This can be written as:

     Func<Developer, bool> filteringPredicate = d => d.Language == "C#";
     Func<Developer, string> selectionPredicate = d => d.Name;
     IEnumerable<string> developersUsingCSharp =
                    developers
                         .Where(filteringPredicate)
                         .Select(selectionPredicate);

Above we have explicitly defined the Func <T,T> delegates. So in

     Func<Developer, bool> filteringPredicate = d => d.Language == "C#";

it is known that d is of Developer type and return type is bool. Similarly, for

     Func<Developer, string> selectionPredicate = d => d.Name;

it is know that d is of Developer type and the return type is string. However in following valid form of the same query how are these types inferred:

IEnumerable<string> developersUsingCSharp =
                      developers
                         .Where(d => d.Language == "C#")
                         .Select(d => d.Name);

Upvotes: 2

Views: 196

Answers (3)

Dan
Dan

Reputation: 9837

The compiler knows that the elements in developers are Developers, so it can infer the first type argument of both lambdas. The compiler can infer the second type arguments by examining the return values of the lambdas: bool for the Where, and string for the Select.

Upvotes: 1

Peter Ritchie
Peter Ritchie

Reputation: 35870

I don't really see a question there; but, have a look at section 7.5.2 of the C# spec. I contains subsections that describe how anonymous and generic method resolution and type inference is performed.

Upvotes: 0

Joshua Honig
Joshua Honig

Reputation: 13215

The compiler knows developers implements IEnumerable<Developer>. This implies that any IEnumerabler<T> extensions off of developers will have items of type Developer.

Upvotes: 3

Related Questions