#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);

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers