Sign in to follow this  
Forcesofevil

C# Events and Delegates

Recommended Posts

frob    44977
The concept of C# delegates is: "When something happens, call me at this function so I can do work."

The concept of C# event class is: "This container holds a bunch of addresses, and the system will call all of them."



They're standard concepts in computer science, and it has been around forever in programming. If you already understand callbacks and function pointers, events and delegates implement the same functionality.

Share this post


Link to post
Share on other sites
Moe    1256
Strangely enough, I found it easier to understand them in terms of function pointers in C++. They can be incredibly useful once you get how to use them though.

Share this post


Link to post
Share on other sites
Telastyn    3777
[quote name='Forcesofevil' timestamp='1302659557' post='4797747']
Anyone have a hard time understanding these concepts? Its really frustrating!
[/quote]

I had quite a bit of trouble with C# 2 when delegate was such an overloaded term. Does delegate mean a strongly typed method signature? Does it mean an anonymous method? Does it mean a function variable?

Now that the strongly typed method signature is nearly never used in favor of Action/Func, and anonymous methods are done via lambdas things are much more clear. Delegates are just function variables again (as they should be).


As for the actual concepts of a function variable or an event... they made a bit of sense, but I knew of them from other languages.

Events are best (initially) viewed in the context of keystrokes or button presses. When I hit 'X' stuff should happen. What stuff? Who knows. Events allow people to specify [b]what [/b]should happen without pressing 'X' themselves.

Delegates are for specifying behaviors. Probably the 'Where' method on collections provides the best context. The actual algorithm for 'get me stuff from a collection that matches... something' is the same. Delegates allow you to pass in a function ([i]code[/i] if you prefer) to fill in that something. Sometimes you want all the even numbers, sometimes all the strings that start with 'foo'. Delegates allow you to write [b]most [/b]of a piece of code and let the caller supply that last little bit of behavior.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this