Sign in to follow this  

How Exactly are events different than delegates? C#

This topic is 3486 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have been learning C# for a while now and I still fail to see what makes delegates different from events? Can someone please explain this to me.

Share this post


Link to post
Share on other sites
An event in C# is a wrapper around a delegate, providing a layer of protection so that public users of a class's event can only add and remove their own methods. You can also implement an event like a property, with your own 'add' and 'remove' methods to store the delegate itself in a different place.

Share this post


Link to post
Share on other sites
A delegate is a kind of a function prototype.

An event is a part of a class that triggers a system message when something happens.

Delegates are used to link events with the methods that handle them.

theTroll

Share this post


Link to post
Share on other sites
A delegate is a function/method pointer.

An event (in its default implementation) is a collection of delegates that is also mimicking as the delegate type it contains. Describing them as multi-cast delegates wouldn't be totally off.

-

Of course, technically, an event in .NET is just a public object field with an add and a remove method that have automatic overrides for operator + and operator -:

class Test {
public event EventHandler SomethingHappened {
add { /* can do anything here */ }
remove { /* can do anything here */ }
}
}


The default implementation simply adds the EventHandler delegate to a collection of delegates on add, removes it from the collection on remove and invokes all delegates in the collection whenever the event is fired.

Share this post


Link to post
Share on other sites

This topic is 3486 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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