Joy Oyiess Rex Karunakaran, who spends some quality times lonely which results this blog.
Saturday, 10 December 2016
Custom Events in C#
What is an event? w
Let us take an easy example,
One fine day, you are returning to your home from the playground. Once reached the home, you felt like starving( not just hungry). And so you reached the kitchen to have some food. Unfortunately the food is not yet prepared (told by your mom). So you went to your bedroom to kill some time, until the food gets ready. Later, you need to know immediately, once the food is prepared.
Where "preparing food" is an event, once it is prepared it will be notified by your mom (EventHandler). So an event handler is alone enough to get notified ? Oh. Wait.
What if your bedroom is in the first floor and kitchen is in the ground floor. On that case, you will be notified through mobile phone, right? (why not?). So you need two more mobiles. OK, lets summarise here, the five major key elements which are responsible
- Event (food preparation)
- Event Handler
To notify)( - Publisher (to send)
- Subscriber (to receive)
- Arguments (Details)
You need to get notified once the food is ready.
Of course, handler is needed to notify you. (where the name of this delegate will be the type of the event, matching colours .)
From which the notifications will be published to all its subscriber . (yes it can be subscribed by many subscribes , which mean your brother will also get notified along with you :p )
Create a separate class for the details you needed. Here i need to know whether the food prepared is vegetarian or not, also how many varieties of dishes are available. You can add as many as properties based on your need.
So now, the system is ready, late take a look at the kitchen.
public class Kitchen {public Kitchen( ) { MakeFood( ); }public void MakeFood( ) { FoodDetailsEventArgs args = new FoodDetailsEventArgs( ); args. TotalDishes = 4; args. IsVeg = False; OnFoodPrepared( args); }public event FoodPreparationEventHandler FoodPrepared;public delegate void FoodPreparationEventHandler( FoodDetailsEventArgs e);public class FoodDetailsEventArgs: EventArgs {public int TotalDishes{ get; set;} public bool IsVeg{ get; set;} }protected virtual void OnFoodPrepared( FoodDetailsEventArgs e) { FoodPreparationEventHandler handler = FoodPrepared;if (handler! = null) {handler ( this, e); } } }
N
public class BedRoom{ Kitchen kitchen;public BedRoom( ){ kitchen = new Kitchen( );kitchen . FoodPrepared +=FoodReady ;} static voidFoodReady ( FoodDetailsEventArgs e){ PersonunToDinningTable . R( );} }
I guess, you won’t understand anything from the above article, In that case refer the MSDN link.
Happy Coding.
Joy Rex.
Subscribe to:
Posts (Atom)