Amaid Niazi
Amaid Niazi

Reputation: 162

Clarification about Events and Delegates in C#

I am learner in C# programming language.I am not able to comprehend the base idea about Events and Delegates. I have viewed numerous tutorials about Events and Delegates however I am still confused about their concept.I additionally don't understand the base point of utilizing events.I know somewhat about Delegates that delegates are similar to function pointers we can call any function utilizing Delegate with same parameters and return type yet why events are used.Can somebody likewise clarify a situation in which it is important to utilize an Event on the grounds that all is well if I don't utilize Events also please explain Is EventHandler a type or a class? in the code below

public static event EventHandler myevent;

Thank You.

Upvotes: 1

Views: 110

Answers (3)

pogojotz
pogojotz

Reputation: 525

EventHandler is a delegate, is a delegate, is a delegate... a function pattern, if you will.

The whole Event and Delegate system is more of a design pattern, which was build into the language. Once you get used to it and start defining your own Delegates and EventArgs you will find it to be pretty convenient. Also their usage is common sense, so you need less documentation, if you want to share your libraries.

Upvotes: 0

bowlturner
bowlturner

Reputation: 2016

Events raise up a flag with something happens, common ones are when you click on a button, it raises an event telling others that 'something' happened. An event handler is there to do something when that event is is raised.

So when you click a button you may want to do something, you set a handler to activate when the button is clicked. You can also have multiple event handlers attached to a specific event, each one doing something different.

The event keyword just a way to create your own 'button clicks' or 'on selection changed' events and the EventHandler lets you catch them and do stuff after that.

Upvotes: 0

Random Dev
Random Dev

Reputation: 52270

If you get delegates than you can think of an event of just being a collection/list of those delegates you will call on demand (if you raise the event) - it's nothing more.

It's a convenient form of letting information flow out of your objects when you don't know (or don't want to know) who might be interested in those informations.

For the second part of your question: EventHandler is just a delegate that gives a common form (the sender of the event and the information as EventArgs)

Upvotes: 1

Related Questions