Q:

C# program to demonstrate the example of generic delegate

belongs to collection: C# Delegate Programs

0

C# program to demonstrate the example of generic delegate

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# program to demonstrate the example of multicast... >>
<< C# program to return the value from the method usi...