C# Functions Part 6 Delegates


This entry is part 6 of 6 in the series C# Functions

A delegate is a type that enables you to store references to functions. Delegates are important parts of events and event handling. Delegates are declared much like functions but with no function body and using the delegate keyword. The delegate declaration specifies a return type and a parameter list.

After defining a delegate you can declare a variable with the type of that delegate. You can then initialize the variable as a reference to any function that has the same return type and parameter list as that delegate. Now you can call that function by using the delegate variable as if it were a function.

When you have a variable that refers to a function you can also perform other operations that would be otherwise impossible. You can pass a delegate variable to a function as a parameter and then that function can use the delegate to call whatever function it refers to without knowing which function will be called until runtime.

// Delegates — Functions
namespace Ch06Ex05
{  // Delegates page 130 - Functions
    class Program    // Delegates - used importantly in Events and Event Handling
                     // Delegates are declared like functions but have no body.
    {   // A delegate is a type that enables you to store references to functions.
        // Delegates are declared like functions but with no function body.
        delegate double ProcessDelegate(double param1, double param2);
        // You can call the delegate name (ProcessDelegate) and parameter names
        // (param1, param2) whatever you like. However the return type and
        // paramter types MUST be the same as you actual function's return type
        // and paramters. 
        static double Multiply(double param1, double param2) => param1 * param2;
        static double Divide(double param1, double param2) => param1 / param2;

        static void Main(string[] args)
        {
            ProcessDelegate process;  // declare a variable with type ProcessDelegate
            WriteLine("Enter 2 numbers separated with a comma:");
            string input = ReadLine();
            int commaPos = input.IndexOf(',');
            // IndexOf reports the zero-based position of the first occurence of the specified Unicode character in the string
            double param1 = ToDouble(input.Substring(0, commaPos));
            // Substring retrieves a substring from this instance, starting character position and length
            double param2 = ToDouble(input.Substring(commaPos + 1, input.Length - commaPos - 1));
            WriteLine("Enter M to multiply or D to divide:");
            input = ReadLine();

            if (input == "M" || input == "m")
                // Initialize the variable as a reference to any function with the same return type
                // and parameter list as the delegate. The variable process references (points to) 
                // a function, which in this case is "Multiply".
                // You can instead use a shortform: process = Multiply;
                process = new ProcessDelegate(Multiply);
            else
                process = new ProcessDelegate(Divide);  // process = Divide;

            WriteLine("Result: {0}", process(param1, param2));
            WriteLine($"Result: {process(param1, param2)}");  // just another way to use WriteLine
            ReadKey();
        }
    }
}
Series Navigation<< C# Functions Part 5 Overloading