Richard's Coding Blog

Richard's Coding Blog

C# Delegates

Delegates and Multicast Delegates

Delegates are a type that indirectly calls a method using a pointer.

This console application implements a multicast delegate called multiCastDel that combines four methods: Add(), Subtract(), Divide() and Multiply().

using System;

namespace Test
{
    //declaring CalculateDel delegate
    delegate void CalculateDel(double a, double b);

    class Program
    {
        //add method
        public static void Add(double first, double second)
        {
            double sum = first + second;
            Console.WriteLine("The sum of {0} and {1} is {2}.", first, second, sum);
        }

        //subtract method
        public static void Subtract(double first, double second)
        {
            double difference = first - second;
            Console.WriteLine("The difference of {0} and {1} is {2}.", first, second, difference);
        }

        //multiply method
        public static void Multiply(double first, double second)
        {
            double multiplier = first * second;
            Console.WriteLine("If you multiply {0} by {1}, the result is {2}.", first, second, multiplier);
        }

        //divide method
        public static void Divide(double first, double second)
        {
            double quotient = first / second;

            //if statement checks if the quotient is infinity
            //note: DivideByZeroException is not possible for floating numbers dividing by zero
            if (double.IsInfinity(quotient))
            {
                Console.WriteLine("Division by zero is not possible. Please enter a divisor value that is not zero.");
            }
            else
            {
                Console.WriteLine("If you divide {0} by {1}, the result is {2}.", first, second, quotient);
            }
        }

        //main method
        static void Main(string[] args)
        {
            //instantiate, create delegate objects
            CalculateDel addDel;
            CalculateDel subDel;
            CalculateDel mulDel;
            CalculateDel divDel;

            //register delegates to a method
            addDel = new CalculateDel(Add);
            subDel = new CalculateDel(Subtract);
            mulDel = new CalculateDel(Multiply);
            divDel = new CalculateDel(Divide);

            //instantiate new multicast delegated 
            CalculateDel multiCastDel;

            //two numbers will be passed through muliCastDel to display... 
            //the results all at once 
            multiCastDel = addDel + subDel + mulDel + divDel;

            //application will loop until user enters -1 when prompted to continue

            //instantiate the prompt value
            double prompt = 0;

            // do while loop for application
            do
            {
                //prompts user for first number
                Console.WriteLine("Please enter the first double number or -1 to discontinue:");
                prompt = Convert.ToDouble(Console.ReadLine());

                if (prompt == -1)
                {
                    //application will end when -1 is entered
                    Console.WriteLine("You have decided to quit the Centennial College Multicast Delegate Application.");
                    Console.WriteLine("Good-bye.");
                    break;
                }
                else
                {
                    //if the first number the user enters is not -1, application will run normally
                    double firstInput = prompt;

                    //prompts user for second number
                    Console.WriteLine("Please enter the second double number:");
                    double secondInput = Convert.ToDouble(Console.ReadLine());

                    //numbers are passed to the multicasted delegate
                    multiCastDel(firstInput, secondInput);

                }
            } while (prompt != -1);

            Console.ReadKey();

        } //end of main method
    }
}

CalculateDel is a global delegate type which represents all void methods that take two double variables as parameters. The four methods (Add, Subtract, Divide and Multiply) have the same signature as the CalculateDel delegate declared in the beginning.

The multiCastDel delegate is an object of CalculateDel which will output results of all four methods at once.

Test output screenshot:

image.png

So, you're probably wondering, "Why do I need to indirectly call methods in the first place?" You didn't really need to actually multicast these four methods with delegates to get the same result.

The point of delegates is to allow easy communication between parties. When you define a delegate, you are essentially allowing any method that matches the signature of the delegate to be called. It would also be a great way of testing methods that you created with the same parameters.

Conclusion

Delegates reference methods with a specific set of parameters and return type. They are object-oriented, they can be passed as parameters and they can even be bundled together into a single event.

 
Share this