Leo Vo
Leo Vo

Reputation: 10330

Please explain about Func delegate in .NET 4.0

In .NET 4.0, have a built-in delegate method:

public delegate TResult Func<in T, out TResult>(T arg);

It is used in LINQ extesion methods, example:

IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

I don't understand clearly about Func delegate, why does the following lambda expression match it:

// p is a XElement object
p=>p.Element("firstname").Value.StartsWith("Q")

Upvotes: 7

Views: 882

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062512

Func<T,TResult> simply means: a method that accepts a T as a parameter, and returns a TResult. Your lambda matches it, in that for T=XElement and TResult=bool, your lambda takes a T and returns a TResult. In that particular case it would commonly be referred to as a predicate. The compiler can infer the generic type arguments (T and TResult) based on usage in many (not all) scenarios.

Note the in and out refer to the (co|contra)-variance behaviour of the method - not the normal usage of out (i.e. out here doesn't mean by-ref, not assumed to be assigned on call, and needs to be assigned before exit).

Upvotes: 12

Connell
Connell

Reputation: 14411

Func<T,TResult> takes two generic parameters: T and TResult. As you can see, T is the type for the arg parameter and TResult is the return type, therefore your code

// p is a XElement object
p=>p.Element("firstname").Value.StartsWith("Q")

Will be a valid Func<XElement, bool>.

The in and out generic modifiers mean that the parameters are contravariant or covariant.

Upvotes: 5

Related Questions