#372 – What Delegates Are Good For

Creating an instance of a delegate that allows you to invoke a method through the delegate doesn’t seem to add much value.  Why not just invoke the method directly?

            // New delegate instance
            LoggerDelegate del1 = Method1;

            // Can still invoke the method directly
            Method1("Direct");

            // Or can invoke through the delegate instance
            del1("Via delegate");

A delegate allows us to treat the reference to the method as a real object, storing it in a variable or passing it to a method as a parameter.  This allows great flexibility, because a method can be told at runtime which child method to call.

        static void DoSomeCalculations(LoggerDelegate log)
        {
            // Do some stuff

            log("I did stuff");

            // Do other stuff

            log("And I did some other stuff");
        }

You then pass in the specific logging method when you invoke DoSomeCalculations and it will call that method.

            DoSomeCalculations(Method1);
Advertisements