pavanarya

Let us share the knowledge

Events in c#

with 3 comments

In my previous post we saw about the creation of Delegates and using them.

Coming to Events in c# they are nothing but a process of notifying the clients when ever something happens.
For example we will have a button in the UI and when we click on it then we will execute something else. How is this going to happen. All this is going to happen with the help of events.

There is a key word that is associated with events that is

event

.

Delegates plays an important role in the creation of events.

Steps For Firing and Subscribing to Events:

Now in this post i want to write about the steps involved in the creation and subscription of events.
Event creation involves a series of steps. Initially we are supposed to create a delegate and then we are supposed to declare an event of the type delegate and then create a method that actually fires the event.Let me explain those steps in brief.

Create a Delegate:

This is the first step involved. Create a class that is going to declare and fire the event.

public delegate void FiringEventHandler(object sender);

Here the delegate type defines the parameters that are supposed to be passed to the method that handles the event.
Here the delegate type can have n number of parameters but the same number of parameter should be there in the function that handles the event.

Declaring the Event:

After creating the delegate the next step would be to declare an event of the type delegate.
There is a reserved keyword for the declaration of the event that is “event”

public event FiringEventHandler FireTheEvent;

Defining the function that fires the event:
This is the most important part of the event creation.
Once a class declares the event that can be used like a field.
Now we are supposed to write a function that is going to fire the event.

public void MethodThatFiresEvent()
        {

            FireTheEvent(this); // This will fire the event
        }

Now we are done with the creation of an event and the definition of a method that fires the event.

Subscribing for the event:
The next step would be to subscribe for the event and define the method that actually handles the event.

Any class can subscribe to the event declared and can define the method that handles the event.

Apart from the class that declared the event , for every other class the event just looks like a field.
But we can perform only two operations on that.

1.Assigning the method that handles the event to the delegate that is defined in the class that fires event
2.Removing any method that is assigned to the delegate

fe.FireTheEvent += new FiringEvent.FiringEventHandler(MyEventHandler);

Here FireTheEvent is the event that is associated with the delegate FiringEventHandler().
MyEventHandler is the method that handles the fired event.
Here MyEventHandler function should have same number of parameters alike the delegate FiringEventHandler(). Ofcource then only that particular method can be assigned to that deleagte or else it is going to throw an error(compile time).

Defining the method that handles the Event:

fe.FireTheEvent += new FiringEvent.FiringEventHandler(MyEventHandler);
public static void MyEventHandler(object sender)
        {
            //code to handle the evnt
        }

Here MyEventHandler() is the method that handles the event.

Last But Not Least Invoking the event:

Now we have everything in our hand that is we are having a class that contains an event and a method that fires the event when called.
A class that subscribed to the event and a method that handles the event.

Now the only thing missing is Calling the method that fires the event in the Class that subscribed to the event.
In our case the method that fires the event is MethodThatFiresEvent() which in turn calls the FireEvent()

fe.MethodThatFiresEvent("pavan", "23");

If we dont call this method that is going to fire the event then our MyEventHandler() will never be called.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EventsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            FiringEvent fe = new FiringEvent();
            fe.FireTheEvent += new FiringEvent.FiringEventHandler(MyEventHandler); //assigning the eventhandler function to the delegate
            fe.MethodThatFiresEvent("pavan", "23");//firing the event
        }

        public static void MyEventHandler(object sender)// Event Handler function
        {
            //code to handle the evnt
           String name=sender.Name;
           String age=sender.age;
        }
    }

    class FiringEvent //Class that creates an event and defines a method that fires the event
    {
        public delegate void FiringEventHandler(object sender);

        public event FiringEventHandler FireTheEvent; //event declaration
        private string name;
        private string age;

        public void MethodThatFiresEvent(string name,string age) //method that fires the event
        {
            this.name = name;
            this.age = age;
            FireTheEvent(this); //This will actually fire the event
        }
    }
}

Note we cannot have this FireTheEvent(this); inside a constructor because if we declare this inside the constructor then the event will be fired immediately when an object is created in the class that handles the event and by that time we cannot assign the event handler function to the event because in order to perform that operation we need the object.

This Doesnt work:

This will not throw any compile time error

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EventsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            FiringEvent fe = new FiringEvent("pavan","21"); // So here itself the event is fired and the event handler method is defined in next step . So the method that handles the event MyEventHandler() is never called
            fe.FireTheEvent += new FiringEvent.FiringEventHandler(MyEventHandler);
        }

        public static void MyEventHandler(object sender)
        {
            //code to handle the evnt
        }
    }

    class FiringEvent
    {
        public delegate void FiringEventHandler(object sender);

        public event FiringEventHandler FireTheEvent;
        private string name;
        private string age;

        public FiringEvent(string name,string age)  //here we are declaring the process of firing the event inside constructor
        {
            this.name = name;
            this.age = age;
            FireTheEvent(this);
        }
    }
}

About these ads

Written by pavanarya

March 25, 2012 at 10:20 pm

Posted in c#

3 Responses

Subscribe to comments with RSS.

  1. hey bro this is randy :D from fb remember …? aww man u got really blogging skillz too :D awsome bro u know how to do coding for a website like script …?

    randy

    March 26, 2012 at 9:55 pm

  2. Great atricle

    We can also submit our dotnet related article links on http://www.dotnettechy.com to improve traffic.

    We can also submit our website / blog in dotnet directory at http://www.dotnettechy.com/dotnet-directory-submit-website.aspx its for dotnet technology related website / blog only

    Micle

    March 27, 2012 at 12:05 pm


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 68 other followers

%d bloggers like this: