blog

Home / DeveloperSection / Blogs / Events in c#

Events in c#

Amit Singh 4271 25-Jan-2011

An event is delivered to an object by means of a call to amethod in that object.  An event isdelegate type class member that is used by the object or class and it provide anotification to other objects that an event has occurred. 

We define the event as

modifiers event type NameOfEvent 

Where modifiersmay be access modifiers like public, protected, private etc.

event is keywordwhich shows the name of event.

type shows theevent declaration which is the name of delegate.

And NameOfEventis a variable. 

For example:

Public event showEventshow; 

Where showEventis delegates and show is event. 

Note: Event isthe part of delegate so first we define the delegate for that event and theninstance of delegate by using keyword event.

How use an event handler

In this example how we implement the event handler

Example:
namespacesampleEvent
{
    //declaration thedelegate here
    public delegate void showName (stringstr);
    class zzz
    {
        //declarationof event
        public event showNameshow;
        public void tEvent()
        {
            if(show != null)
                show("checkthe event");
        }
    }
    class Program
    {
        static void Main(string[]args)
        {
            zzzz = new zzz();
            Programp = new Program();
            z.show+=newshowName(p.z_show);
            z.tEvent();
        }
        public void z_show(stringstr)
        {
            Console.WriteLine(str);
            Console.ReadLine();
        }
    }}

Output:

check the event



c# c# 
Updated 18-Sep-2014

Leave Comment

Comments

Liked By