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")
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.
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With