View Full Version : Why use delegates?
BobLewiston
02-26-2009, 11:32 PM
Why use delegates?
I understand HOW to use delegates, but in what situations would you actually use them? The examples I see in the literature are all in situations where the code could just be written without ever using them.
Fou-Lu
02-26-2009, 11:46 PM
Delegates and function pointers are used to ensure that developers write code to handle certain features without knowing or needing to understand the original underlying code.
A good example is a sorting routine that uses a callback. The developer performing the sort doesn't need to know how the sort actually occurs (could be a quick sort, radix sort, heap sort, etc), but my code doesn't know how to compare (or can be programmed so I don't even care the datatype), so I tell them I want a method that returns an int and takes in two instances of x, where x can be an object or other pointer type. All they need to do is write that method and provide it with the list. What the underlying code will do is perform the comparisons using this method, and since the delegate or function pointer matches my signature I know it will return a 0, positive or negative number.
PHP and C/C++ make extensive use of function pointers and callbacks. C# (delegates) and Java don't really do this as much and prefer to follow a decorator style handling for these.
oracleguy
02-27-2009, 12:36 AM
In C# another area they are used in is with events. Which are basically lists of function pointers.
For example, if you have a class that is processing a lot of data, you might want to be able to indicate which record it is on. Take the following delegate as an example:
public delegate progressStatusDelegate(string record);
And if your class had the following event:
public event progressStatusDelegate progressChange
When you change your record, you just need to call your event which is using the function pointers stored in the event list. So you do something like:
progressChange("Some record X");
Your class doesn't need to know what gets done with it, if anything (events don't necessarily have anything in the list). So you could have a function in your GUI that matches the delegate and it displays the string in the status bar.
Events are one of the ways that the uses for delegates really comes out.
As Fou-Lu mentioned earlier they are also used in callbacks. If you have an asynchronous function, you need to use a callback to indicate when it is complete. You wouldn't want to write a different version of the function every time you wanted to call a different function. It works with one of the rules of OOP which is "closed for modification, open for expansion".
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.