Please explain the Func delegate in .NET 4.0.

.NET 4.0 has a built-in delegation method:

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

It is used in LINQ extension methods, for example:

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

I clearly don't understand the Func delegate why the following lambda expression matches it:

 // p is a XElement object p=>p.Element("firstname").Value.StartsWith("Q") 
+7
source share
2 answers

Func<T,TResult> simply means: a method that takes T as a parameter and returns a TResult . Your lambda matches it, in this for T=XElement and TResult=bool your lambda takes T and returns a TResult . In this particular case, it is usually called a predicate. The compiler can output general type arguments ( T and TResult ) based on use in many scenarios (not all).

Note that in and out refer to the behavior of the (co | contra) -variance of the method - not the normal use of out (i.e., out is not > mean by-ref, which is not supposed to be assigned by call, and must be assigned before exiting )

+12
source

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

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

It will be a valid Func<XElement, bool> .

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

+5
source

All Articles