Multicast Delegates

A delegate that points to multiple methods is called a multicast delegate. The + operator adds a function to the delegate object and the - operator removes an existing function from a delegate object.
When the multicast delegate is called, it invokes the delegates in the list, in order. Only delegates of the same type can be combined.


namespace Delegates 
{
    delegate void ArithmeticOperation(double operand1, double operand2);

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

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

        static void Multiplication(double number1, double number2)
        {
            System.Console.WriteLine($"{number1} * {number2} = {number1 * number2}");
        }

        static void Division(double number1, double number2)
        {
            System.Console.WriteLine($"{number1} / {number2} = {number1 / number2}");
        }

        static void Main(string[] args)
        {
            ArithmeticOperation operations = Addition;
            operations += Subtraction;
            operations += Multiplication;
            operations += Division;
            operations(10, 5);
            System.Console.WriteLine();
        }
    }
}


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext