Handle an Event with an Anonymous Function - CSharp Custom Type

CSharp examples for Custom Type:Event

Description

Handle an Event with an Anonymous Function

Demo Code

using System;//from   w ww .  j ava 2 s. co m
class MainClass
{
   public static EventHandler MyEvent;
   static void Main(string[] args)
   {
      // use a named method to register for the event
      MyEvent += new EventHandler(EventHandlerMethod);
      // use an anonymous delegate to register for the event
      MyEvent += new EventHandler(delegate(object sender, EventArgs eventargs)
      {
         Console.WriteLine("Anonymous delegate called");
      });
      // use a lamda expression to register for the event
      MyEvent += new EventHandler((sender, eventargs) =>
      {
         Console.WriteLine("Lamda expression called");
      });
      Console.WriteLine("Raising the event");
      MyEvent.Invoke(new object(), new EventArgs());
   }
   static void EventHandlerMethod(object sender, EventArgs args)
   {
      Console.WriteLine("Named method called");
   }
}

Result


Related Tutorials