tags:

views:

1210

answers:

8

Possible Duplicates:
Delegate Usage : Business Applications
Where do I use delegates?

Hi,

I'm new to the concept of a delegate in .NET - I haven't really used them yet and think they are probably there for a good reason - when should I be using a delegate?

Examples are very welcome.

+1  A: 

Events use delegates behind the scenes.

If you use events you've used delegates but just with a nicer syntax.

Basically one use for them is for callbacks or event based programming.

Finglas
+1  A: 

Delegates are used for event driven programming. Best practices are often about decoupling code (or 'loose' coupling). Using delegates you can subscribe methods to events, instead of having X call Y if something happens, and then Y call Z under a certain condition and so forth.

Alex
+1  A: 

Delegates are useful when you need to tell another piece of code how to do something. Events are the simplest example - separating the event (something happened) from how to handle it. Other examples are some common iterative operations, such as a custom find:

List<Foo> foos = new List<Foo>();
foos.Find(delegate(Foo foo)
    {
        if(foo.CustomProperty.Contains("special value"))
        {
            return false;
        }
        return true;
    });

The above is a totally arbitrary example but makes the point that you can separate the what (iterating and running a "find" criteria) from the how (how to determine whether something is found).

Rex M
+2  A: 

Delegates provide a way for you to pass behavior as a parameter.

Common examples are Events and asynchronous programming where something other than your object is responsible for calling into your object. You provide that event with a delegate, and now it's able to run the behavior associated with that delegate.

This can also be a useful technique when implementing a general algorithm. There've been times where I'm writing multiple methods that are very similar. Perhaps they loop over the same set of data, but they perform slightly different tasks. I can pass in a delegate to a single function to perform that task, then call the delegate from inside the loop over the data. This way I don't have to implement the loop over the data multiple times, I only have to write new code that does new things-- the common behavior is all captured in a common way.

In response to the comment:

The difference between calling the delegate from within the loop and calling the method from within the loop is that the delegate is a parameter to the function that contains the loop. This means that that function could do anything, not just what's defined within a particular method. That flexibility can and has been leveraged to supply generic algorithms in libraries completely independent of the specifics of what the algorithms are working with. Linq is a fine example of the generality that is allowed via the flexibility of delegates.

Greg D
Your answer is a little vague for me. what is the difference between calling a delegate from withing the loop and calling a simple method from within that loop?
yn2
A: 

Events and Callbacks in the .NET guidelines explains it well.

In summary, you should prefer events in simple APIs because there is strong IDE support and most developers are comfortable with events. However, if you need the user to provide code that will be executed, you should consider using delegates or virtual members. Callbacks are less performant, but if you use delegates like Action and Func you allow lambdas.

OwenP
+1  A: 

Also, I would recommend using generic delegate types instead of creating your own. Examples below:

EventHandler< TEventArgs>
Func< TResult>
Func< T1, T2, TResult>
Func etc...
Action< T1>
Action< T1, T2>
Action etc...

Aaron Hoffman
Aaron- that's a good point. The Framework Design Guidelines now state you should avoid creating custom delegates- http://blogs.msdn.com/brada/archive/2009/01/26/framework-design-guidelines-avoiding-custom-delegates.aspx
RichardOD
A: 

Also, besides all that has been said by others, lambda expressions in newer versions of .NET are directly based on delegates.

petr k.
+1  A: 

Example case: a single resource is being used by multiple objects. The resource needs an asynchronous callback to these objects, but the nature of the resource demands that only one request be active at a given time, and that request is tied to a particular object. Due to the architecture, I don't want to pass the objects into the resource, so instead, I send the resource a delegate from each object and store these delegates along with object identifiers. When a request is made, I can look up the corresponding object identifier and call its specific delegate.

I originally implemented this with an event, but since the event couldn't be 'aimed' at a particular object, I was having issues. I'm not sure this is best practice, but it seems to work well for me.

genki