How do I create a Delegate/MulticastDelegate?

C# requires only a single parameter for delegates: the method address. Unlike other languages, where the programmer must specify an object reference and the method to invoke, C# can infer both pieces of information by just specifying the method's name. For example, let's use

System.Threading.ThreadStart: Foo MyFoo = new Foo();

ThreadStart del = new ThreadStart(MyFoo.Baz);

This means that delegates can invoke static class methods and instance methods with the exact same syntax!

Editorial / Best Answer

Answered by: Raghu

  • Sep 29th, 2005


This article is good.

Introduction


In this article I am going to share my knowledge on Delegates in C#.This would explain the Delegate using simple examples so that the beginner can understand the same.


What is Delegate?


Definition:

Delegate is type which  holds the method(s) reference in an object.
it is also reffered as a type safe function pointers.

Advantages:
.Encapsulating the method's call from caller
.Effective use of Delegat improves the performance of application.
.used to call a method asynchronously.

Declaration:

public delegate type_of_delegate delegate_name()

Example : public delegate int mydelegate(int delvar1,int delvar2)

Note:
.you can use delegeate without parameter or with parameter list
.you should follow the same syntax as in the method
(if you are reffering the method with two int parameters and int return type the delegate which you are declaring should be the same format.This is how it
is reffered as type safe function pointer)

Sample Program using Delegate :

public delegate double Delegate_Prod(int a,int b);

class Class1
{


static double fn_Prodvalues(int val1,int val2)
  {
return val1*val2;
  }
static void Main(string[] args)
{


//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);


Console.Write("Please Enter Values");

int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());

//use a delegate for processing

double res = delObj(v1,v2);
Console.WriteLine ("Result :"+res);
Console.ReadLine();

}
}


Explanation:

Here I have used a small program which demonstrates the use of delegate.

The delegate "Delegate_Prod" is declared with double return type and which accepts only two integer parameters.

Inside the Class the method named fn_Prodvalues is defined with double return type and two integer parameters.(The delegate and method is having the same signature and parameters type)

Inside the Main method the delegate instance is created and the function name is passed to the
delegate instance as following.

Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);

After this we are accepting the two values from the user and passing those values to the delegate as we do using method .

delObj(v1,v2);

Here  delegate object encapsulates the method functionalities and return the result as we specified
in the method.


Multicast Delegate


What is Multicast Delegate? :
It is a Delegate which holds the reference of more than one methods.
Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate
----------------------------------------

delegate void Delegate_Multicast(int x, int y);

Class Class2

{
static void Method1(int x, int y) {
 Console.WriteLine("You r in Method 1");
}
static void Method2(int x, int y) {
 Console.WriteLine("You r in Method 2");
}
public static void Main()
{
 Delegate_Multicast func = new Delegate_Multicast(Method1);

 func += new Delegate_Multicast(Method2);
 func(1,2);             // Method1 and Method2 are called
 func -= new Delegate_Multicast(Method1);
 func(2,3);             // Only Method2 is called
}

}
                           

Explanation:

In the above example you can see that two methods are defined named method1 and method2 which takes two integer parameters and return type as void.

In the main method the Delegate object is created using the following statement


Delegate_Multicast func = new Delegate_Multicast(Method1);

Then the Delegate is added using the += operator and removed using -= operator.



Showing Answers 1 - 4 of 4 Answers

Raghu

  • Sep 29th, 2005
 

This article is good.

Introduction


In this article I am going to share my knowledge on Delegates in C#.This would explain the Delegate using simple examples so that the beginner can understand the same.


What is Delegate?


Definition:

Delegate is type which  holds the method(s) reference in an object.
it is also reffered as a type safe function pointers.

Advantages:
.Encapsulating the method's call from caller
.Effective use of Delegat improves the performance of application.
.used to call a method asynchronously.

Declaration:

public delegate type_of_delegate delegate_name()

Example : public delegate int mydelegate(int delvar1,int delvar2)

Note:
.you can use delegeate without parameter or with parameter list
.you should follow the same syntax as in the method
(if you are reffering the method with two int parameters and int return type the delegate which you are declaring should be the same format.This is how it
is reffered as type safe function pointer)

Sample Program using Delegate :

public delegate double Delegate_Prod(int a,int b);

class Class1
{


static double fn_Prodvalues(int val1,int val2)
  {
return val1*val2;
  }
static void Main(string[] args)
{


//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);


Console.Write("Please Enter Values");

int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());

//use a delegate for processing

double res = delObj(v1,v2);
Console.WriteLine ("Result :"+res);
Console.ReadLine();

}
}


Explanation:

Here I have used a small program which demonstrates the use of delegate.

The delegate "Delegate_Prod" is declared with double return type and which accepts only two integer parameters.

Inside the Class the method named fn_Prodvalues is defined with double return type and two integer parameters.(The delegate and method is having the same signature and parameters type)

Inside the Main method the delegate instance is created and the function name is passed to the
delegate instance as following.

Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);

After this we are accepting the two values from the user and passing those values to the delegate as we do using method .

delObj(v1,v2);

Here  delegate object encapsulates the method functionalities and return the result as we specified
in the method.


Multicast Delegate


What is Multicast Delegate? :
It is a Delegate which holds the reference of more than one methods.
Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate
----------------------------------------

delegate void Delegate_Multicast(int x, int y);

Class Class2

{
static void Method1(int x, int y) {
 Console.WriteLine("You r in Method 1");
}
static void Method2(int x, int y) {
 Console.WriteLine("You r in Method 2");
}
public static void Main()
{
 Delegate_Multicast func = new Delegate_Multicast(Method1);

 func += new Delegate_Multicast(Method2);
 func(1,2);             // Method1 and Method2 are called
 func -= new Delegate_Multicast(Method1);
 func(2,3);             // Only Method2 is called
}

}
                           

Explanation:

In the above example you can see that two methods are defined named method1 and method2 which takes two integer parameters and return type as void.

In the main method the Delegate object is created using the following statement


Delegate_Multicast func = new Delegate_Multicast(Method1);

Then the Delegate is added using the += operator and removed using -= operator.



Anirban Saha

  • May 10th, 2016
 

This is incorrect. You can assign any type of methods to a multicast delegate and it wont throw any exception.

Code
  1.     delegate int Delegate_Multicast(int x, int y);

  2.     class Program

  3.     {

  4.         static int Method1(int x, int y)

  5.         {

  6.             Console.WriteLine("You r in Method 1");

  7.             return x + y;

  8.         }

  9.         static int Method2(int x, int y)

  10.         {

  11.             Console.WriteLine("You r in Method 2");

  12.             return x * y;

  13.         }

  14.         static void Main(string[] args)

  15.         {

  16.             Delegate_Multicast func = new Delegate_Multicast(Method1);

  17.             func += new Delegate_Multicast(Method2);

  18.             int abc = func(1, 2);

  19.             Console.WriteLine(abc);

  20.             func -= new Delegate_Multicast(Method1);

  21.             int bcd = func(2, 3);

  22.             Console.WriteLine(bcd);

  23.         }

  24.     }

  25.  

  Was this answer useful?  Yes

Rajesh Muurya

  • Aug 9th, 2016
 

I have some doubt.
Raghus Says: Delegate is type which holds the method(s) reference in an object.
My question is if Delegate is type then how we create a object of delegate? Because, we know that we can create object only struct and class.

  Was this answer useful?  Yes

Naveen Kumar Shivanadri

  • Sep 8th, 2016
 

Delegate is not type. It is just pointer method which is used to improve the performance. Suppose we want to execute a method 10 times by using calling method by using class name or instance, 10 times stack will be created by the time of method execution starts and destroy 10 times immediate after method execution complete. To avoid this creation and destroy the stack, delegates came to the picture.

Using the delegates by following 3 steps
1). Delegate definition.
< access modifier > delegate < return type/Non return type > < delegate name >([prameterlist]);
example :
public delegate void/int DelName(int a,int b);
2). Bound with the method with delegate.
< delegate Name > < delegate variable > =new < delegateName >(< method name >);
or
< delegate Name > < delegate variable > =< method name >;
example :
DelName dn = new DelName(addmethod);
or
DelName dn = instance.addmethod;
Note : return type of method and parameter list(type,order,number of parameter) should be same for method and delegate.

3). calling the delegate
< delegate variable >([parameterlist]);
example : dn(10,20);

in the multicast delegate, we will bind more than one method and call all of them at a time just calling the delegate variable.
Note : all the method return type should be void and parameter list should be same.

dn+=instance.submethod, dn+=instance.mulmethod

Naveen Kumar Shivanadri.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions