Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 632
Leo Vo Avatar asked Nov 01 '11 08:11

Leo Vo


People also ask

What is func delegate?

Func is a delegate that points to a method that accepts one or more arguments and returns a value. Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.

What is the use of Func delegate in C#?

Func is generally used for those methods which are going to return a value, or in other words, Func delegate is used for value returning methods. It can also contain parameters of the same type or of different types.

What is delegate in .NET explain with an example?

Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.

What is delegate in .NET C#?

C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.


2 Answers

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).

like image 200
Marc Gravell Avatar answered Oct 04 '22 11:10

Marc Gravell


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.

like image 44
Connell Avatar answered Oct 04 '22 10:10

Connell