#372 – What Delegates Are Good For
July 21, 2011 9 Comments
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);
Nice work, thank you Sean.
Shouldn’t you pass del1 instead of Method1 as the argument? As far as I understood from your post that’s the whole point of delegate!
You’d pass an instance of a delegate–which could be assigned (like del1), or just the method name (like the 3rd code fragment example).
But Method1 is not an instance of a delegate, is it?
No
Kristof, note that you can pass either a delegate instance or a method name to a function that has a delegate type as one of its parameters. (E.g. DoSomeCalculations()). Similar to if you had a parameter of type int and you could either pass a integer typed variable or just an integer constant. You can think of the method name as like a delegate type constant.
Sean, thanks for this. It wasn’t obvious to me at first, but I think I understand the significance now of using the delegate to use pass a method as an argument. To follow up, would there need to be an instance of a delegate declared for each method before it is passed? (which seems, odd and unintuitive) Assuming you don’t have to, could you then pass any method through the delegate parameter?
Thanks Mike. No, you don’t need to define a delegate instance at all, but just pass the method name to the method that takes a delegate type as a parameter. A delegate instance will get created for you.
Thank you, I’ve never understood the use of delegates before! Been on your blog all day.