Where do I use delegates? [closed]

What are some real world places that call for delegates? I'm curious what situations or patterns are present where this method is the best solution. No code required.


Solution 1:

As stated in "Learning C# 3.0: Master the fundamentals of C# 3.0"

General Scenario: When a head of state dies, the President of the United States typically does not have time to attend the funeral personally. Instead, he dispatches a delegate. Often this delegate is the Vice President, but sometimes the VP is unavailable and the President must send someone else, such as the Secretary of State or even the First Lady. He does not want to “hardwire” his delegated authority to a single person; he might delegate this responsibility to anyone who is able to execute the correct international protocol.

The President defines in advance what responsibility will be delegated (attend the funeral), what parameters will be passed (condolences, kind words), and what value he hopes to get back (good will). He then assigns a particular person to that delegated responsibility at “runtime” as the course of his presidency progresses.

In programming Scenario: You are often faced with situations where you need to execute a particular action, but you don’t know in advance which method, or even which object, you’ll want to call upon to execute it.

For Example: A button might not know which object or objects need to be notified. Rather than wiring the button to a particular object, you will connect the button to a delegate and then resolve that delegate to a particular method when the program executes.

Solution 2:

A delegate is a named type that defines a particular kind of method. Just as a class definition lays out all the members for the given kind of object it defines, the delegate lays out the method signature for the kind of method it defines.

Based on this statement, a delegate is a function pointer and it defines what that function looks like.

A great example for a real world application of a delegate is the Predicate. In the example from the link, you will notice that Array.Find takes the array to search and then a predicate to handle the criteria of what to find. In this case it passes a method ProductGT10 which matches the Predicate signature.

Solution 3:

One common use of delegates for generic Lists are via Action delegates (or its anonymous equivalent) to create a one-line foreach operation:

myList.Foreach( i => i.DoSomething());

I also find the Predicate delegate quite useful in searching or pruning a List:

myList.FindAll( i => i.Name == "Bob");    
myList.RemoveAll( i => i.Name == "Bob");

I know you said no code required, but I find it easier to express its usefulness via code. :)

Solution 4:

Binding Events to Event Handlers is usually your first introduction to delegates...You might not even know you were using them because the delegate is wrapped up in the EventHandler class.