concept Func in category .net

appears as: Func
Rx.NET in Action

This is an excerpt from Manning's book Rx.NET in Action.

Lambda expressions are used heavily with Rx because they make your processing pipeline short and expressive, which is cool! But you still have the requirement to create new delegate types each time you want to specify a method signature for the method types to which you want to receive a reference, which is far from ideal. That’s why you usually won’t create new delegate types but instead use Action and Func.

This works pretty well, but it’s annoying, because each time you want a new comparison method, you need to create a new class. Instead, you can use the power of Func and create a generic IComparer that you can tune to your needs:

This is somehow an adapter between the IComparer and Func. To use it, you pass the required comparison code as a lambda expression (or delegate):

  • Func is a delegate type that returns a value and can receive parameters.
  • Whenever you need to create a delegate for methods that return a value, you should use the type Func. This type (like Action) receives a variable number of generic parameters corresponding to the types of parameters that the method referenced by the delegate can receive. Unlike Action, in the Func definition the last generic parameter is the type of return value:

    public delegate TResult Func<in T1,...,T16, out TResult>(T1 arg,...,T16 arg16);

    and there’s a definition for a Func that gets no parameters:

    public delegate TResult Func<out TResult>();

    Using Func, you can extend your implementation of the ForEach method so that it’ll accept a filter (also known as a predicate). The filter is a method that accepts an item and returns a Boolean indicating whether it’s valid: