Loading...

C# 3.0 includes built-in generic delegate types Func, so that you don't need to define our own custom delegates.

Func is a generic delegate included in the System namespace. It has zero or more than one input parameters and one out parameter. The last parameter is an out parameter.

namespace System{    
    public delegate TResult Func<in T, out TResult>(T arg);
}

The last parameter in the angle brackets <> is the return type and remaining 
parameter is input parameter type.


We can assign any method to the func delegate that takes two int parameters and returns an int value. 
Now, we take Func delegate instead of some Operation delegate in the first example.

class Program
{
    static int Sum(int x, int y)
    {
        return x + y;
    }
    static void Main(string[] args)
    {
        Func<int,int, int> add = Sum;
        int result = add(10, 10);
        Console.WriteLine(result); 
    }
}


A Func delegate type can include 0 to 16 input parameters of different types. However, it must include one out parameter for return type. For example, the following func delegate doesn't have any input parameter, it includes only a out parameter.

Func<int> getRandomNumber = delegate()
{
Random rnd = new Random();
        return rnd.Next(1, 100);
};


Func with Lambda Expression

A Func delegate can also be used with a lambda expression, as shown below:

Func<int> getRandomNumber = () => new Random().Next(1, 100);


Advantages of Func Delegates

  1. Easy and quick to define delegates.
  2. Makes code short.
  3. Compatible type throughout the application.

Things to be remember when using Func :

  1. Func is built-in delegate type.
  2. Func delegate type must return a value.
  3. Func delegate type can have zero to 16 input parameters.
  4. Func delegate does not allow ref and out parameters.
  5. Func delegate type can be used with an anonymous method or lambda expression.