C# Program to Create Generic Delegate
Posted by Superadmin on August 14 2022 03:31:41

C# Program to Create Generic Delegate

 

This is a C# Program to check whether the entered number is even or odd.

Problem Description

This C# Program Creates Generic Delegate.

Problem Solution

Here code that references the generic delegate can specify the type argument to create a closed constructed type, just like when instantiating a generic class or calling a generic method.

Program/Source Code

Here is source code of the C# Program to Create Generic Delegate. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Create Generic Delegate
 */
using System;
using System.Collections.Generic;
delegate T NumberChanger<T>(T n);
namespace GenericDelegateAppl
{
    class TestDelegate
    {
        static int num = 10;
        public static int AddNum(int p)
        {
            num += p;
            return num;
        }
 
        public static int MultNum(int q)
        {
            num *= q;
            return num;
        }
        public static int getNum()
        {
            return num;
        }
 
        static void Main(string[] args)
        {
            NumberChanger<int> nc1 = new NumberChanger<int>(AddNum);
            NumberChanger<int> nc2 = new NumberChanger<int>(MultNum);
            nc1(25);
            Console.WriteLine("Value of Num: {0}", getNum());
            nc2(5);
            Console.WriteLine("Value of Num: {0}", getNum());
            Console.ReadKey();
        }
    }
}
Program Explanation

This C# program, we are creating delegate instances using ‘nc1’ and ‘nc2’ variables respectively and compute the methods using the delegate objects.

 
Generic allows delaying the specification of the data type of programming elements in a class or a method, until it is actually used in the program.

Here Code that references the generic delegate can specify the type argument to create a closed constructed type, just like when instantiating a generic class or calling a generic method.

Runtime Test Cases
 
Result of the Addition : 35 
Result of the Product : 175