views:

92

answers:

4

Possible Duplicates:
C# - Can someone tell me why and where I should use delegates?
C# Delegates Real World Usage

While searching for answers here on stackoverflow, many of the code examples use Delegates. What are they? How they work? when, why and how to use them? Please give some simple code examples

A: 

Delegates are basically first-class functions.

That is, they are functions which stand alone as their own entities in the program, as opposed to being tied to another entity such as a class.

If you have C/C++ background, it is acceptable to think of them as a strongly-typed .NET equivalent to function pointers.

jdmichal
I doubt this explanation would be useful to the OP as it assumes some previous knowledge.
ChaosPandion
+1  A: 

Objective-C delegates are simple abstraction pattern. It's described very on WikiPedia.

Troy Sandal
+1  A: 

A delegate is more than one thing in C#:

  • A delegate type is a type which similar to an interface with a single method.
  • A delegate instance can be called like a method except that you can attach and detach handlers to it at runtime instead of it having a method body defined at compile time. If there are multiple handlers invoking the delegate will result in all the handlers being called (assuming no exception is thrown).

Jon Skeet's article on events and delegates covers this in more depth.

Mark Byers