find and solve || findandsolve.com
Please wait.....

Func delegate in C#

In C#, Func is a generic delegate included in the System namespace and has zero or more input parameters and one out parameter. Others include Predicate and Action. Func can be used with a method.

The Func delegate that takes one input parameter and one out parameter is defined in the System namespace like as given below:


Signature: Func

namespace System

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

The last parameter in the angle brackets <> is considered the return type, and the remaining parameters are considered input parameter types


The given Func delegate example takes two input parameters of int type and returns a value of int type:

Func<int, int, int> sum;

We can assign any method to the above func delegate that takes two int parameters and returns an int value.

using System;

public class Program
{
 static Func<int,int, int> operation;
 public static int AddNumber(int a, int b)
    {
        return a + b;
    }
 public static void Main()
 {
  Func<int,int, int> add = AddNumber;
        int result = add(12, 17);
        Console.WriteLine(result);
 }
}

Output

29


Func with Zero Input Parameter

Func<int> obj;


C# Func with an Anonymous Method

We can assign an anonymous method to the Func delegate by using the delegate keyword as given below.

Func with Anonymous Method

 Func<int> obj= delegate()

   {
   Random rnd = new Random();
   return rnd.Next(1, 200);
  };


Func with Lambda Expression

A Func delegate can also be used with a lambda expression like as given below code.

using System;

public class Program
{
 public static void Main()
 {
  Func<int> obj = () => new Random().Next(1,200);
  Func<int, int, int> Sum = (a, b) =>a + b;
  Console.WriteLine(obj());
  Console.WriteLine(Sum(14,13));
 }
}

Output

22

27


Points to Remember :

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