Friday, February 12, 2010

How to add Custom Event Handler for UDTs (User Defined Types)

Today one of my friend asked me how to add custom events to our custom class.With simple example i explained to him then  I thought i can blog his question and Answer. Here is the example i used

Suppose let say we have UDT Called  Contact with the following properties Name, Phone , Email, and Address. suppose we want to notified if some one changes Contact Phone number property .

First let us define UDT as C# Class.

public class Contact
{
private string phone = string.Empty;
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }

// Define the event for Phone number change.
public event EventHandler PhoneChanged;
public string Phone
{
get
{
return phone;
}
set
{
this.phone = value;
if (this.PhoneChanged != null) //Check to see event is not null
this.PhoneChanged(this , new EventArgs());
}
}


}



Now let see how we can invoke this event from code.



namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
Contact c = new Contact();
c.PhoneChanged += new EventHandler(c_PhoneChanged);
c.FirstName = "Sreeni";
c.LastName = "Ramadurai";
c.Address= "123 Main Street";
c.Phone = "214-499-2837"; // Here i am setting (changing) the phone number.
c.PhoneChanged+=new EventHandler(c_PhoneChanged);
}

static void c_PhoneChanged(object sender, EventArgs e)
{
Console.WriteLine("PhoneChanged");

Contact c = (Contact)sender; //we need to cast here
Console.WriteLine(c.Phone ); // Display the phone number.
}
}




     image  



Nandri(Thanks)



SreenivasaRagavan.

No comments: