Where do I use delegates?

slipsec picture slipsec · Aug 28, 2008 · Viewed 45.4k times · Source

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.

Answer

Atish Dipongkor picture Atish Dipongkor · Jun 26, 2013

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.