tags:

views:

284

answers:

7

I understand delegates encapsulate method calls. However I'm having a hard time understanding their need. Why use delegates at all, what situations are they designed for?

+4  A: 

Delegates are often used for Events. According to MSDN, delegates in .NET are designed for the following:

  • An eventing design pattern is used.
  • It is desirable to encapsulate a static method.
  • The caller has no need access other properties, methods, or interfaces on the object implementing the method.
  • Easy composition is desired.
  • A class may need more than one implementation of the methodimplementation of the method

Another well put explenation from MSDN

One good example of using a single-method interface instead of a delegate is IComparable or IComparable. IComparable declares the CompareTo method, which returns an integer specifying a less than, equal to, or greater than relationship between two objects of the same type. IComparable can be used as the basis of a sort algorithm, and while using a delegate comparison method as the basis of a sort algorithm would be valid, it is not ideal. Because the ability to compare belongs to the class, and the comparison algorithm doesn’t change at run-time, a single-method interface is ideal.single-method interface is ideal.

Since .NET 2.0 it has also been used for anonymous functions.

Wikipedia has a nice explenation about the Delegation pattern

In software engineering, the delegation pattern is a design pattern in object-oriented programming where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object. It passes the buck, so to speak (technically, an Inversion of Responsibility). The helper object is called the delegate. The delegation pattern is one of the fundamental abstraction patterns that underlie other software patterns such as composition (also referred to as aggregation), mixins and aspects.

Filip Ekberg
+8  A: 

Well, some common uses:

  • Event handlers (very common in UI code - "When the button is clicked, I want this code to execute")
  • Callbacks from asynchronous calls
  • Providing a thread (or the threadpool) with a new task to execute
  • Specifying LINQ projections/conditions etc

Don't think of them as encapsulating method calls. Think of them as encapsulating some arbitrary bit of behaviour/logic with a particular signature. The "method" part is somewhat irrelevant.

Another way of thinking of a delegate type is as a single-method interface. A good example of this is the IComparer<T> interface and its dual, the Comparison<T> delegate type. They represent the same basic idea; sometimes it's easier to express this as a delegate, and other times an interface makes life easier. (You can easily write code to convert between the two, of course.)

Jon Skeet
A: 

Delegates allow you to pass a reference to a method. A common example is to pass a compare method to a sort function.

Brian Rasmussen
+5  A: 

They are designed, very broadly speaking, for when you have code that you know will need to call other code - but you do not know at compile-time what that other code might be.

As an example, think of the Windows Forms Button.Click event, which uses a delegate. The Windows Forms programmers know that you will want something to happen when that button is pressed, but they have no way of knowing exactly what you will want done... it could be anything!

So you create a method and assign it to a delegate and set it to that event, and there you are. That's the basic reasoning for delegates, though there are lots of other good uses for them that are related.

Andrew Barber
+9  A: 

Delegate is basically a Method Pointer. A delegate lets us create a Reference Variable, but instead of referring to an instance of a Class, it refers to a Method inside the class. It refers any method that has a return type and has same parameters as specified by that delegate. It's a very very useful aspect of Event. For thorough reading I would suggest you to read the topic in Head First C#. It beautifully explains the Delegate topic as well as most concepts in dotnet.

sumit_programmer
awesome description..
shrikant.soni
A: 

If you need to decide at runtime, which method to call, then you use a delegate. The delegate will then respond to some action/event at runtime, and call the the appropriate method. It's like sending a "delegate" to a wedding you don't want to attend yourself :-)

The C people will recognize this as a function pointer, but don't get caught up in the terminology here. All the delegate does (and it is actually a type), is provide the signature of the method that will later be called to implement the appropriate logic.

The "Illustrated C#" book by Dan Solis provides the easiest entry point for learning this concept that I have come across:

http://www.amazon.com/Illustrated-2008-Windows-Net-Daniel-Solis/dp/1590599543

IrishChieftain
While I happen to be very fond of Apress... whats the use of linking a "not yet published" book?
WernerCD
@WernerCD, thanks for the heads-up. There are two previous editions so am updating link :-)
IrishChieftain
I absolutely love C# Illustrated 2008 and happen to be waiting for 2010 to get released... it was the first thing I noticed heh :)
WernerCD
It was the 2005 version of this book that finally helped me get my head around delegates :-)
IrishChieftain
A: 

A delegate is typically a combination of an object reference and a pointer to one of the object's class methods (delegates may be created for static methods, in which case there is no object reference). Delegates may be invoked without regard for the type of the included object, since the included method pointer is guaranteed to be valid for the included object.

To understand some of the usefulness behind delegates, think back to the language C, and the printf "family" of functions in C. Suppose one wanted to have a general-purpose version of "printf" which could not only be used as printf, fprintf, sprintf, etc. but could send its output to a serial port, a text box, a TCP port, a cookie-frosting machine, or whatever, without having to preallocate a buffer. Clearly such a function would need to accept a function pointer for the character-output routine, but that by itself would generally be insufficient.

A typical implementation (unfortunately not standardized) will have a general-purpose gp_printf routine which accepts (in addition to the format string and output parameters) a void pointer, and a pointer to a function which accepts a character and a void pointer. The gp_printf routine will not use the passed-in void pointer for any purpose itself, but will pass it to the character-output function. That function may then cast the pointer to a FILE* (if gp_printf is being called by fprintf), or a char** (if it's being called by sprintf), or a SERIAL_PORT* (if it's being called by serial_printf), or whatever.

Note that because any type of information could be passed via the void*, there would be no limit as to what gp_printf could do. There would be a danger, however: if the information passed in the void* isn't what the function is expecting, Undefined Behavior (i.e. potentially very bad things) would likely result. It would be the responsibility of the caller to ensure that the function pointer and void* are properly paired; nothing in the system would protect against incorrect usage.

In .net, a delegate would provide the combined functionality of the function pointer and void* above, with the added bonus that the delegate's constructor would ensure that the data was of the proper type for the function. A handy feature.

supercat