Action Delegate

Action Delegate

What is an Action Delegate?

C# 3.0 introduced built-in generic delegate types Func and Action so that we don't have to declare custom delegates. These are included in the System namespace. Action delegate in C# represents a delegate that has void return type and optional parameters. An Action delegate can take up to 16 input parameters of different types.

using System;

namespace ActionDelegate
{
    class Program
    {
        static void Addition(double number1, double number2)
        {
            Console.WriteLine($"{number1} + {number2} = {number1 + number2}");
        }

        static void Subtraction(double number1, double number2)
        {
            Console.WriteLine($"{number1} - {number2} = {number1 - number2}");
        }

        static void Main(string[] args)
        {
            Action<double,double> opr; //This line changed
            
            opr = Addition;
            opr(10, 5);

            opr = Subtraction;
            opr(10,5);

            Console.WriteLine();
        }
    }
}

An anonymous method can also be assigned to Action delegate as below

using System;

namespace ActionDelegate
{
    class Program
    {
        static void Main(string[] args)
        {
            Action<double,double> sum;
            sum = delegate (double number1, double number2)
            {
                Console.WriteLine($"{number1} + {number2} = {number1 + number2}");
            };

            sum(10, 5);
            Console.WriteLine();
        }
    }
}

A lambda expression can also be used with Action delegate as below:

using System;

namespace ActionDelegate
{
    class Program
    {
        static void Main(string[] args)
        {
            Action<double,double> sum;            
           
            //braces are optional, since only one statement in the function body
            sum = (n1, n2) => Console.WriteLine($"{n1} + {n2} = {n1 + n2}");            
            
            sum(10, 5);

            Console.WriteLine();
        }
    }
}

Additional Reading

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

Last updated