Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate pointing to multiple function with different signatures [closed]

Tags:

c#

delegates

How can a single delegate point to multiple function which will have different signature?

suppose i have a two functions whose signature is different.

private int Add(int x,int y)
{
   return (x+y);
}

private int MultiplyByTwo(int x)
{
   return (x*2);
}

please tell me is it possible with single delegate to point Add & multiple two different function at a time and function will call according to argument.

please discuss with code and also tell me how to perform the same job with func<> delegate.

thanks

like image 581
Thomas Avatar asked Feb 23 '26 14:02

Thomas


2 Answers

This is not possible. The point of a delegate is to act as a strongly typed function pointer (loosely put), and nor will the runtime do any guessing as to what should be called depending on the parameters. If that is the type of functionality you are looking for, you might be interested in the dynamic keyword in C# 4.

All delegates inherit from a common delegate called Delegate, if that is the functionality you are looking for.

static void Main(string[] args)
{
    Delegate method1 = new Action<string>(PrintOneString);
    Delegate method2 = new Action<string, string>(PrintTwoString);
    method1.DynamicInvoke("Hello");
    method2.DynamicInvoke("Hello", "Goodbye");
}

public static void PrintOneString(string str)
{
    Console.WriteLine(str);
}

public static void PrintTwoString(string str1, string str2)
{
    Console.WriteLine(str1);
    Console.WriteLine(str2);
}
like image 73
vcsjones Avatar answered Feb 26 '26 03:02

vcsjones


As the others already said, the signature of those methods are different. You can map the Add method to a Func<int, int, int> delegate:

Func<int, int, int> add = calculator.Add;

And you can map the MultiplyByTo method to a Func<int, int> delegate:

Func<int, int> multiply = calculator.MultiplyByTo;

You can map the Add method to a Func<int, int> delegate, but you need to fill in the missing argument:

Func<int, int> add5 = x => calculator.Add(x, 5);
like image 34
Steven Avatar answered Feb 26 '26 03:02

Steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!