Smartssolutions

Wednesday, October 5, 2011

A senario of implementing a custom event

In this blog I will represent two senario of implementing a custom event one without arguments and other with arguments

Hi
Here is a full implementation of both senarios when using event args and when using a custom event args to pass some information when raising events
namespace ConsoleApplication1
{  
  class Program
  {
    static void Main(string[] args)
    {
      //Without arguements
      EventClass eventClass = new EventClass();
      eventClass.CustomEvent+=new EventHandler(eventClass_CustomEvent);

      //With arguements
      EventWithArguementsClass eventwithargclass = new EventWithArguementsClass();
      eventwithargclass.CustomEvent+=new EventWithArguementsClass.CustomEventHandler(eventwithargclass_CustomEvent);
      Console.Read();
    }

    static void eventClass_CustomEvent(object sender, EventArgs args)
    {
      Console.WriteLine("The event is raised");
    }

    static void eventwithargclass_CustomEvent(object sender, CustomEventArgs args)
    {
      args.Message = "The event with parameters is raised";
      Console.WriteLine(args.Message);
    }

  }//Class

  //Class sample with event args, used when you don't need to pass some information throught
  class EventClass
  {
    private event EventHandler customEvent;

    public event EventHandler CustomEvent
    {
      add { customEvent += value; OnCustomEvent(); }
      remove { customEvent -= value; }
    }

    protected void OnCustomEvent()
    {
      if (null!= customEvent)
      {
        customEvent(this, new EventArgs());
      }
    }

  }//Class
  //Class sample with event args, used when you need to pass some information throught like the message
  class EventWithArguementsClass
  {
    public delegate void CustomEventHandler(object sender, CustomEventArgs args);
    private event CustomEventHandler customEvent;
    private string message=string.Empty; 

    public event CustomEventHandler CustomEvent
    {
      add { customEvent += value; OnCustomEvent(message); }
      remove { customEvent -= value; }
    }

    protected void OnCustomEvent(string message)
    {
      if (null != customEvent)
      {
        customEvent(this, new CustomEventArgs(message));
      }
    }

  }
  class CustomEventArgs:EventArgs
  {
    public string Message { get; set; }

    public CustomEventArgs(string message)
    {
      Message = message;
    }
  }



No comments:

Post a Comment