C# program to demonstrate the example of generic delegate

Here, we are going to learn about the generic delegate and its C# implementation. By Nidhi Last updated : April 03, 2023

C# Example of Generic Delegate

Here, we will create a generic delegate then we can specify the type of argument and call methods using delegates.

C# code for generic delegate

The source code to demonstrate the generic delegate is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate generic delegate.

using System;

using System.Collections.Generic;
delegate T MyDel<T>(T n1, T n2);

class Sample
{ 
    static int Add(int num1, int num2)
    {
        return(num1+num2);
    }

    static int Sub(int num1, int num2)
    {
        return (num1-num2);
    }

    static int Mul(int num1, int num2)
    {
        return (num1*num2);
    }

    static int Div(int num1, int num2)
    {
        return (num1/num2);
    }

    static void Main()
    {
        int result = 0;
        int num1   = 0;
        int num2   = 0;

        MyDel<int> del1 = new MyDel<int>(Add);
        MyDel<int> del2 = new MyDel<int>(Sub);
        MyDel<int> del3 = new MyDel<int>(Mul);
        MyDel<int> del4 = new MyDel<int>(Div);

        Console.Write("Enter the value of num1: ");
        num1 = int.Parse(Console.ReadLine());

        Console.Write("Enter the value of num2: ");
        num2 = int.Parse(Console.ReadLine());

        result = del1(num1,num2);
        Console.WriteLine("Addition:       " + result);

        result = del2(num1, num2);
        Console.WriteLine("Subtraction:    " + result);

        result = del3(num1, num2);
        Console.WriteLine("Multiplication: " + result);

        result = del4(num1, num2);
        Console.WriteLine("Division:       " + result);
    }
}

Output

Enter the value of num1: 8
Enter the value of num2: 5
Addition:       13
Subtraction:    3
Multiplication: 40
Division:       1
Press any key to continue . . .

Explanation

In the above program, we created a Sample class that contains five static methods Add(), Sub(), Mul(), Div(), and Main() method.

MyDel<int> del1 = new MyDel<int>(Add);
MyDel<int> del2 = new MyDel<int>(Sub);
MyDel<int> del3 = new MyDel<int>(Mul);
MyDel<int> del4 = new MyDel<int>(Div);

In the above code, we created generic delegates and bind methods. Then read the value variables num1 and num2, and then called methods using generic delegates and print the result on the console screen.

C# Delegate Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.