Most Viewed

Most Viewed

Sunday 15 July 2012

Example on Delegate, Multicast delegate, Events in C#.Net


Demonstrates delegate in C#.Net
using System;
class Class1
{     public delegate int Calc(int a,int b);
              static int  Multi(int val1,int val2)
              {return val1*val2;}
              static void Main(string[] args)
              {     Calc  delObj = new  Calc(Multi);
Console.Write("Enter val1:");int v1 = Int32.Parse(Console.ReadLine());
Console.Write("Enter val2:");int v2= Int32.Parse(Console.ReadLine());
              int val=delObj(v1,v2);
              Console.WriteLine ("Mutiplication :"+val);
              Console.Read();
              }

}

Demonstrate Multicast delegate in C#.Net
using System;
class Client1
{public void mesg(string s)
       { Console.WriteLine("Mesg to client1:"+s);}
}
class Client2
{public void mesg(string s)
       { Console.WriteLine("Mesg to client2:"+s);}
}
class Client3
{public void mesg(string s)
       {Console.WriteLine("Mesg to client3:"+s);}
}
public class Class1
{     delegate void DelClient (string s);
       public static void Main()
       {
       DelClient del=new DelClient(new Client1().mesg);
         del+=new DelClient(new Client2().mesg);
         del+=new DelClient(new Client3().mesg);
       del("Meeting at 11 am");
       Console.Read();
       }
}

Demonstrating event handling technique in C#.Net
using System;
class EventSource
{     public delegate void EventDelegate();
       public event EventDelegate myEvent;
       public void eventRaiser(){myEvent();}
}
       class EventListener
       {     static void Main(string[] args)
              {
                     EventSource es=new EventSource();
       es.myEvent+=new EventSource.EventDelegate(myEventHandler);
                     es.eventRaiser();
                     Console.Read();
              }
              private static void myEventHandler()
              {
              Console.WriteLine("Event Handler is called!");
               }
       }

No comments:

Post a Comment