Delegate Usefulness
by XanthorXIII · in Torque X 2D · 12/04/2009 (8:31 pm) · 2 replies
I've been reading up on delegates and I am trying to figure out their usefulness when programming in C#.
Does it go something along the lines of being able to pass a method to another method and call it within that method?
I guess I'm just not seeing it because some of the examples I've found out on the Internet and in some books have been simple examples like creating simple add and subtract methods. It just seems like another thing that adds to the complexity of coding where it shouldn't be complex to begin with.
Does it go something along the lines of being able to pass a method to another method and call it within that method?
I guess I'm just not seeing it because some of the examples I've found out on the Internet and in some books have been simple examples like creating simple add and subtract methods. It just seems like another thing that adds to the complexity of coding where it shouldn't be complex to begin with.
About the author
It's alive!
#2
Yes.
They're useful because you can pass any method of any object in providing it's signature matches that of the delegate, so you can switch methods at runtime, as often as you like, maybe when the state of an object changes or whatever. Not only that, unlike C++ function pointers, .NET delegates are multicast, meaning one delegate can hold a reference to multiple methods, and when you invoke the delegate, all methods are called. They're seriously useful and far easier than C++ function pointers.
12/06/2009 (11:59 pm)
Quote:Does it go something along the lines of being able to pass a method to another method and call it within that method?
Yes.
They're useful because you can pass any method of any object in providing it's signature matches that of the delegate, so you can switch methods at runtime, as often as you like, maybe when the state of an object changes or whatever. Not only that, unlike C++ function pointers, .NET delegates are multicast, meaning one delegate can hold a reference to multiple methods, and when you invoke the delegate, all methods are called. They're seriously useful and far easier than C++ function pointers.
Torque Owner Duncan Colvin
An example in TX is delegates used for collisions and stuff like that. I also use them in my own custom GUI framework to assign actions. The uses of delegates are many and varied :)