2

I've learnt from here that dynamic variables cannot access methods on interfaces they explicitly implement. Is there an easy way to invoke the interface methods when I don't know the type parameter T at compile time?

interface I<T>
{
    void Method1(T t);
}

class C<T> : I<T>   
{   
    void I<T>.Method1(T t) 
    { 
        Console.WriteLine(t);
    }
}

static void DoMethod1<T>(I<T> i, T t)
{
    i.Method1(t);
}

void Main()
{
    I<int> i = new C<int>();
    dynamic x = i;
    DoMethod1(x, 1);              //This works
    ((I<int>)x).Method1(2);       //As does this
    x.Method1(3);                 //This does not
}      

I don't know the type parameter T, so (as far as I know) I can't cast my dynamic variable x. I have lots of methods in the interface, so don't really want to create corresponding DoXXX() pass through methods.

Edit: Note that I don't control and cannot change C or I.

Community
  • 1
  • 1
Rob
  • 4,327
  • 6
  • 29
  • 55

1 Answers1

0

You can do this via reflection:

I<int> i = new C<int>();
dynamic x = i; // you dont have to use dynamic. object will work as well.
var methodInfo = x.GetType().GetInterfaces()[0].GetMethod("Method1");
methodInfo.Invoke(x, new object[] { 3 });
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • I can probably do something with reflection, but the type `C` implements multiple generic interfaces, and there are various overloads of some of the methods, so it's not easy. – Rob Apr 15 '15 at 16:15