Users Online

· Guests Online: 103

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C# Program to Create Generic Delegate

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

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.02 seconds
10,831,320 unique visits