Search code examples
c#reflectiontypesinterfaceidatareader

How to invoke a method which returns an interface


I am invoking a method on a type via reflection which takes a couple of parameters:

var myType = typeof(myClass);

var myMethod = myType.GetMethod("myMethodInClass", 
                                 new[] { typeof(string), typeof(string) });

myMethod.Invoke(?, new object[] { "", "" });

I want the target to be an IDataReader, which is what the method will return, but I obviously cannot instantiate a new instance of an interface.


Solution

  • Where you have put ? in the the question should not be IDataReader, but an instance of myClass. You are passing in the object on which you want to invoke myMethod.

    The result from calling .Invoke() will be an IDataReader, but that is not something you are creating; it is created inside the method you are invoking.