Before diving into sample,lets discuss few basic things related to Event,Delegates and EventArgs.
EventArgs- Eventargs is nothing but the actual data that we pass to subscribers when certain event takes place.The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.
Delegate-In C#,we define delegate with Handler suffix.Right,but what is that?For me,its like a pipeline between a certain event raiser and event handler.It is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke (or call) the method through the delegate instance. Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method and a class such as a windows control can call your method when a certain event occurs.
But Why do we need it?
the code needing to perform the action doesn't know the method to call when it's written. You can only call the method directly if you know at compile-time which method to call, right? So if you want to abstract out the idea of "perform action X at the appropriate time" you need some representation of the action, so that the method calling the action doesn't need to know the exact implementation ahead of time.
Events - An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. The most familiar use for events is in graphical user interfaces; typically, the classes that represent controls in the interface have events that are notified when the user does something to the control (for example, click a button).
Events are just properties (like the get;set; properties to instance fields) which expose subscription to the delegate from other objects. These properties, however don't support get;set;. Instead they support add;remove;
So you can have:
Action myField;
public event Action MyProperty
{
add { myField += value; }
remove { myField -= value; }
}
Join the conversation! Your thoughts help the community grow.