What is Generic Delegate in C#?

DWQA QuestionsCategory: C SharpWhat is Generic Delegate in C#?
Editor Staff asked 11 months ago

What is Generic Delegate in C#?

1 Answers
Editor Staff answered 11 months ago

A generic delegate can be defined the same way as a delegate but using generic type parameters or return type. The generic type must be specified when you set a target method.
For example, consider the following generic delegate that is used for int and string parameters.

Example: Generic Delegate

public delegate T add<T>(T param1, T param2); // generic delegate

class Program
{
    static void Main(string[] args)
    {
        add<int> sum = Sum;
        Console.WriteLine(sum(10, 20));

        add<string> con = Concat;
        Console.WriteLine(conct("Hello ","World!!"));
    }

    public static int Sum(int val1, int val2)
    {
        return val1 + val2;
    }

    public static string Concat(string str1, string str2)
    {
        return str1 + str2;
    }
}