Nov 27, 2012

Create custom events in c#

Create custom event in C# and handle them


Consider the following code.

public class FeedsManager
{
    public event Status onStatusChange;
    public delegate void Status(string StatusText, int StatusPercent);

public void someMethod(){
 ......
 ........
 if (onStatusChange!= null) onStatusChange("Starting...", 10);
 .......
 .......
 ........
 if (onStatusChange!= null) onStatusChange("Starting...", 10);
 .......
 }
.
.
.
//other methods...
}



1. Declare the event delegate 

public delegate void Status(string StatusText, int StatusPercent);

As in this case Status is the event type taking two arguments one of type string and other integer. you can provide a custom name to event and pass many arguments of different types.

2.  Now create the event

   public event Status onStatusChange;

Create an event of the type of delegate you have created , here the name of event is  onStatusChange.


3. Raising the event

if (onStatusChange!= null) onStatusChange("Starting...", 10);

first we have to check is an event handler is set, if yes then call the handler function and pass the desired arguments.

Note: you can raise a event as many time you want, but in the context of same class.


Creating the handlers for event.

  FeedsManager FM = new FeedsManager();

 FM.onStatusChange += new FeedsManager.Status(FM_onStatusChange);
        
 void FM_onStatusChange(string StatusText, int StatusPercent)
        {
       //do what ever you want
        }


Or alternatively you can create a handler function as


 FM.onStatusChange += (msg, per) => {
           //do whatever you want
       };


Hope it helps you some where 
happy coding.... :D

No comments:

Post a Comment