Sunday, September 30, 2007

How events work in C#

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).

namespace Event
{
class Program
{
static void Main(string[] args)
{
EventRaiser eventRaiser = new EventRaiser();
ClassA classA = new ClassA();

/*
* Subscribing to an Event
*/
//Events with Static method
eventRaiser.raised += ClassB.Method;

//Events with instantiated object
eventRaiser.raised += classA.Method;

//Method which raise the event
eventRaiser.RaiseEvent();

Console.ReadLine();

}

}

class EventRaiser
{ //Declaring an Event
public event EventHandler raised;

public void RaiseEvent()
{
EventRaiserMethod(null, EventArgs.Empty);
}
private void EventRaiserMethod(object obj, EventArgs e)
{ if (raised != null)
{
Console.WriteLine("I am in the Event");
raised(obj, e);
}
}

public EventRaiser()
{

}
}

class ClassA
{
public void Method(object obj, EventArgs sender)
{
Console.WriteLine("I am in Method of Class A");
}

}

class ClassB
{
public static void Method(object obj, EventArgs sender)
{
Console.WriteLine("I am in Method of Class B");
}
}
}

No comments: