C# chokes on
delegate void Bar<T>(T t);
void foo(Bar bar)
{
bar.Invoke("hello");
bar.Invoke(42);
}
The workaround is to use an interface
interface Bar
{
void Invoke<T>(T t);
}
but now I need to go out of my way to define the implementations of the interface. Can I achieve the same thing with delegates and simple methods?
This is not possible because you cannot assign an open generic method to a delegate. It would be an interesting new feature to suggest, but currently C# does not allow it.
Possible workarounds:
delegate void Bar(object t);
void foo(Bar bar)
{
bar.Invoke("hello");
bar.Invoke(42);
}
void BarMethod(object t)
{
if (t is int)
// ...
else if (t is string)
// ...
}
foo(BarMethod);
delegate void Bar<T>(T t);
void foo(Bar<string> stringBar, Bar<int> intBar)
{
stringBar.Invoke("hello");
intBar.Invoke(42);
}
void BarMethod<T>(T t)
{
// ...
}
foo(BarMethod<string>, BarMethod<int>);
The interface workaround you already mentioned:
interface IBar
{
void Invoke<T>(T t);
}
void foo(IBar bar)
{
bar.Invoke("hello");
bar.Invoke(42);
}
class BarType : IBar
{
public void Invoke<T>(T t)
{
// ...
}
}
foo(new BarType());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With