Sunday, June 26, 2011

Custom Events in C# - Basic Example

Creating custom events are very tough for me until i have started writing few custom events for my application. Here i wanted to share the way i have learned writing Custom Events. I hope, it will help the others too.

Before we go into the example, let me list out the concepts we need to know.

1. delegates, also called as function pointers

2.
event keyword

3. Event arguments

4. += and -= operators.

Thats it. We should know what are these and what functionality they provide.

A custom event can be implemented in 7 steps
1. Define event arguments , using which we can pass some information along with the event. Normally we have to create a class extending
EventArgs with required members. One of the best practice to suffix our class name with 'EventArgs', so that readability and maintainability will be more.

2. Create the Class on which you wanted to raise the event.

3. Define a delegate which will accept the event handler from the class which is intended to receive and handle this event. basically this delegate defines the signature of the event handler method that target application has to use.

4. create event member by using
event keyword and specify the event name. Whatever the name we uses here, will be visible to clients while adding the event handler.

5. Include the logic to call the event. Basically this part provides the link between event and it's handler. Based some condition(that's where event is raised) we will call event handler.

6. In client application, Add event handler using += operator. we can use -= operator to unregister the event.

7. Implement the event handler method to provide the logic that ehat should happen if the event fires.

Here is the Example,
Car Speed Controller Example. This is all about, if the car exceeds 60KMPH then warn the user saying Car speed is exceeding 60KMPH.

#Step1
Creating a class for passing event arguments.

//CarSpeedEventArgs.cs - Step 1
namespace CarSpeedControllerEvents
{
public class CarSpeedEventArgs
{
private string _message;

public CarSpeedEventArgs(string strMessage)
{
_message = strMessage;
}

public string Message
{
get
{
return _message;
}
}
}
}

//Car.cs
namespace CarSpeedControllerEvents
{
//Step 2
public class Car
{
private Int32 _CarSpeed;

public Car()
{
_CarSpeed = 0;
}

//Step 3
public delegate void CarSpeedController(object sender, CarSpeedEventArgs data);

//Step 4
public event CarSpeedController SpeedController;

public Int32 CarSpeed
{
set
{
_CarSpeed = value;

//Step 5
if (_CarSpeed > 60)
{
try
{
CarSpeedEventArgs objArgs = new CarSpeedEventArgs("Warning : Car speed exceeded 60KMPH");
SpeedController(this, objArgs);
}
catch { }
}
}
}

}
}

namespace CarSpeedControllerEvents
{
class Program
{
static void Main(string[] args)
{
Car myCar = new Car();

//Step 6 - Registering with event
myCar.SpeedController += ControlCalSpeed;

Console.WriteLine(" Car Current speed : 75KMPH");
myCar.CarSpeed = 75;
Console.WriteLine(" Car Current speed : 25KMPH");
myCar.CarSpeed = 25;
Console.WriteLine(" Car Current speed : 61KMPH");
myCar.CarSpeed = 61;

//Unregistering with event
myCar.SpeedController -= ControlCalSpeed;
Console.WriteLine(" Car Current speed : 81KMPH");
myCar.CarSpeed = 81;//This statement won't fire an event

Console.ReadLine();

}

//Step 7
public static void ControlCalSpeed(object sender, CarSpeedEventArgs data)
{
Console.WriteLine("\t ==> {0}", data.Message.ToString());
}
}
}

 

No comments:

Post a Comment