Delegate Part(2)
Contents:
In this article following content would be covered
- Multi Cast Delegate
1.Multi Cast Delegate
- class Name
- {
- public void Print()
- {
- Console.WriteLine("My Name is Usman Arshad");
- }
- }
- //Class 2
- class Country
- {
- public void Print()
- {
- Console.WriteLine("I am from Pakistan");
- }
- }
- //Main Class
- namespace
- {
- public delegate void Multicastdelegate();
- class Program
- {
- Name obj = new Name();
- Country obj1 = new Country();
- Multicastdelegate delegate = new Multicastdelegate(obj.Print); //Reference of the print method of class Name
- delegate= delegate + new Multicastdelegate(obj1.Print); //Just use '+' sign to add more methods
- obj1.Invoke();
- }
- }
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