Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic delegates

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?

like image 648
Bruno Martinez Avatar asked Oct 05 '10 22:10

Bruno Martinez


1 Answers

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());
like image 159
Timwi Avatar answered Nov 17 '22 02:11

Timwi