Function Delegate

Func delegate is used for value returning methods.

  • It can contain minimum 0 and maximum of 16 input parameters in it and it must contain one output parameter.

  • The last parameter of the Func delegate is the output parameter or result parameter.

  • It can also contain parameters of the same type or of different types.

using System;

namespace FuncDelegate
{
    class Program
    {
        static double Addition(double number1, double number2)
        {
            return number1 + number2;
        }

        static void Main(string[] args)
        {
            Func<double,double,double> sum = Addition;
            var result = sum(10, 5);
            Console.WriteLine(result);
        }
    }
}

Anonymous method with Func delegate

using System;

namespace FuncDelegate
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<double, double, double> sum = delegate (double number1, double number2)              
            {
                return number1 + number2;
            };
            var result = sum(10, 5);
            Console.WriteLine(result);
        }
    }
}

Func delegate With lambda

using System;

namespace FuncDelegate
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<double, double, double> sum = (double number1, double number2) => number1 + number2; 
            var result = sum(10, 5);
            Console.WriteLine(result);
        }
    }
}

Additional Reading

https://itnext.io/delegates-anonymous-methods-and-lambda-expressions-5ea4e56bbd05

Last updated