In C#, delegates represent methods that are callable without knowledge of the target object. Delegates enable scenarios that some other languages have addressed with function pointers. However, unlike function pointers, delegates are object-oriented and type-safe.
There are three steps in defining and using delegates: declaration, instantiation, and invocation.
static double fn_Prodvalues(int val1,int 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);
Here I have used a small program which demonstrates the use of delegate.
The delegate “Delegate_Prod” is declared with double return type and 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 have the same signature and parameter type.)
Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows:
After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:
Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.
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
In the above example, you can see that two methods are defined named method1 and method2 which take two integer parameters and return type as void.
In the main method, the Delegate object is created using the following statement:
Then the Delegate is added using the += operator and removed using the -= operator.
Delegates and interfaces are similar in that they enable the separation of specification and implementation. Multiple independent authors can produce implementations that are compatible with an interface specification. Similarly, a delegate specifies the signature of a method, and authors can write methods that are compatible with the delegate specification. There are direction defined by Microsoft when to use delegate and when to use interface.
Delegates are ideally suited for use as events – notifications from one component to “listeners” about changes in that component.