Func, Action and lambda

In this chapter you will learn:

  1. How to use Func, Action and lambda
  2. Example for lambda expression from Func, Action

Description

lambda expression are often used with Func and Action delegates.

Func and Action are predefined delegates with generic parameters.


delegate TResult Func <out TResult>  ();
delegate TResult Func <in T, out TResult>  (T arg);
delegate TResult Func <in T1, in T2, out TResult>  (T1 arg1, T2 arg2);
// www  .  ja  v a2s  . c om
... and so on, up to T16

delegate void Action  ();
delegate void Action <in T>  (T arg);
delegate void Action <in T1, in T2>  (T1 arg1, T2 arg2);

... and so on, up to T16

Example

Here is an example of how use to use Func to create a lambda expression.


using System;//from   w ww  .  j av  a2 s  .  c  o  m


class Program
{
    public static void Main()
    {

        Func<int, int> sqr = x => x * x;

        Console.WriteLine(sqr(3));
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. What are Lambda Capturing Outer Variables
  2. Example for Lambda Capturing Outer Variables
  3. Captured variables evaluation
  4. Update captured variables
  5. Lifetime of Captured variables
Home »
  C# Tutorial »
    C# Types »
      C# Lambda
C# Lambda Expressions
Func, Action and lambda
C# Lambda Capturing Outer Variables