3

This is a weird problem that I've stumbled upon, involving reflection:

I create a MyGenericType<T> at runtime where T is a runtime type:

object genType = Activator.CreateInstance(typeof(MyGenericType<>).MakeGenericType(runtimeType));

Then I need to pass it as an argument to another function which only accepts a IEnumerable<runtimeType>.

I can't use dynamic as MyGenericType only implements IEnumerable explicitly, not implicitly.

Is there anyway to cast to an IEnumerable<runtimeType>?

Yair Halberstadt
  • 5,733
  • 28
  • 60

1 Answers1

3

Create a generic caller method and invoke that instead. In my code sample, the CallMethod is invoked via reflection and that method invokes the method that takes an IEnumerable<T>

static void Main(string[] args)
{
    Type runtimeType = typeof(string);

    object genType = Activator.CreateInstance(typeof(MyGenericType<>).MakeGenericType(runtimeType));

    var genericMethod = ((Action<MyGenericType<object>>)CallMethod)
        .Method
        .GetGenericMethodDefinition()
        .MakeGenericMethod(runtimeType)
        .Invoke(null, new object[] { genType });
}

static void CallMethod<T>(MyGenericType<T> myGeneric)
{
    MyEnumerableMethod((IEnumerable<T>)myGeneric);
}
Grax32
  • 3,986
  • 1
  • 17
  • 32