2

Can I create a delegate that would behave like this?

// here I have delegate
delegate ... MyDel ...

MyDel del = SomeMethod; // or even lambda?
int number = del<int>(...);

As an idea, it's probably a duplicate question, but I'm pointing at this ->

int n = del<int>(...);

So, can a delegate be generic function? If not (and I'm pretty sure it can't), why is it implemented this way? In what cases could it be a problem?

skeletank
  • 2,880
  • 5
  • 43
  • 75
werat
  • 59
  • 1
  • 7

4 Answers4

2

No, a delegate instance cannot point to an open generic method.

I can only speculate why this is so, but I'd assume that the cost of this language feature does not outweigh its benefits, given that it'll probably not be used often. See Eric Lippert's answer here on how features get into C#.

Community
  • 1
  • 1
dtb
  • 213,145
  • 36
  • 401
  • 431
2

Delegates do not allow such functionality; for that you need to define an interface; some examples:

interface IActOnAnything
{
  void Invoke<T>(T it)
}
interface IActOnAnything<TP1>
{
  void Invoke<T>(T it, TP1 p1)
}
interface IActOnAnythingByRef
{
  void Invoke<T>(ref T it)
}

Unfortunately, there's no language support to facilitate implementation of such interfaces. If a class will only need to define one function which implements the interface, one could simply declare the implementation at the class level. Otherwise, one should probably declare for each implementation a nested private class which implements the interface and holds an object of its parent type.

supercat
  • 77,689
  • 9
  • 166
  • 211
0

Yes it is possible, like Func, Action, and also you can make your own:

delegate TOutput MyDelegate<TInput,TOutput>(TInput input);

MyDelegate<string, int> myDelegate = input=>input.Length;

Also you can do this:

int n = new MyDelegate<string, int>(input => input.Length)("MY STRING"); //n=9
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
0

Yes, it's possible:

public delegate int Test<T>(T input) where T : struct;

public static event Test<int> TestEvent;

static void Main(string[] args)
{
    var n = TestEvent(5);
}
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263