Delegates, Events and Events args

In our previous post on delegate, events and Events Args we talked discussed what each is and its role in event driven programming. In this post we present the code representation of the previous post.  So without wasting too much time and keeping you waiting we immediately starting on presentation of the code based on our previous discussion.

EventArgs are used to contain the additional information that should be passed from the event to the event handler.  And to encapsulate the additional information we will extend the EventArgs class and add the information we want the doctor to know about the Patient.  To have it simple we will need the first and last name for the patient.

internal class PatientArgs : EventArgs
 public PatientArgs(string firstName, string lastName)
 FirstName = firstName;
 LastName = lastName;
 public string FirstName { get; set; }
 public string LastName { get; set; }

So far so good, huh? We need to have our Patient class now in place. Remember it is the patient who should raise the alert that he has arrived. Also its important to note the Event declaration. In my case I am using the generic delegate EventHandler<TEventArgs> which represent a method that will used to handle the event provides data.

 internal class Patient
 //Event arriving
 public event EventHandler<PatientArgs> Arrived;

public void OnPatientArrived()
 if (Arrived != null)
 Arrived(this, new PatientArgs("", ""));

So clients(Doctors) interested in knowing when a Patient arrives should subscribe to Arrived event, which you can simply see it done in the next snippet. So you can see clearly that Program provides an handler to the event as to when a patient arrives. So what happens is that when the patient arrived “p_Arrived” will run. Note that one of the parameter for p_Arrived is PatientArgs which carries the FirstName and LastName of the patient. You are not limited to the number of information you want passed to the Event handler in the EventArgs.

class Program
 public static void p_Arrived(object sender, PatientArgs e)
 Console.WriteLine(string.Format("Attending {0} {1}", e.FirstName, e.LastName));
 static void Main(string[] args)
 Patient p = new Patient();
 p.Arrived += p_Arrived;

There you have it . Happy coding :).


About Piusn

Enthusiastic Software Developer

What's your thought on the subject?

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: