Thursday, 17 December 2015

Delegate Part 2

                                 Delegate Part(2)


Contents:
 In this article following content would be covered
  1. Multi Cast Delegate

     1.Multi Cast Delegate
"A delegate that contains multiple methods are Multi Cast Delegate. 

We use multi cast delegate when there is need of invoking multiple events like we want to print a string and at the same time we want to write this string in the file or that purpose we use multi cast delegate.


Note: These events are invoked in which  sequence you called them. For example there are two events print and read .The order in which read and print would be invoked depends upon the order in which you would call them(events).


 Example1:


//Class 1

  1.  class  Name
  2.     {
  3.         public void Print()
  4.         {
  5.             Console.WriteLine("My Name is Usman Arshad");
  6.         }
  7.     }

  8. //Class 2

  9. class Country
  10.     {
  11.         public void Print()
  12.         {
  13.             Console.WriteLine("I am from Pakistan");
  14.         }

  15.     }

  16. //Main Class
  17. namespace
  18. {

  19. public delegate void Multicastdelegate();
  20.  class Program
  21.     {
  22.  Name obj = new Name();
  23.     Country obj1 = new Country();
  24.             Multicastdelegate delegate = new Multicastdelegate(obj.Print);  //Reference of the print method of class Name
  25.             delegate= delegate + new Multicastdelegate(obj1.Print);      //Just use '+'  sign to add more methods
  26.                 obj1.Invoke();
  27.            }
  28. }









OutPut
My Name is Usman Arshad
I am from Pakistan

You can also write the statement no 30 like this
delegate+=new Multicastdelegate(obj1.Print);

Common Error

A common error which mostly beginner do is that when you pass the reference the method to the delegate object just pass the method name ,do not use function syntax .For example
  Multicastdelegate delegate = new Multicastdelegate(obj.Print( ));
This is a syntax error.Because you only need the name of the method not the method itself

In the next article ,I will write about Call-Back Methods.











No comments:

Post a Comment