Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Cast object to IList<T> based on Type

I am trying out a little reflection and have a question on how the cast the result object to an IList.

Here is the reflection:

private void LoadBars(Type barType)
{
    // foo has a method that returns bars
    Type foo = typeof(Foo);

    MethodInfo method = foo.GetMethod("GetBars")
        .MakeGenericMethod(bar);

    object obj = method.Invoke(foo, new object[] { /* arguments here */ });
    // how can we cast obj to an IList<Type> - barType
}

How can we cast the result of method.Invoke to an IList of Type from the barType argument?

like image 298
blu Avatar asked Mar 22 '10 14:03

blu


2 Answers

The point of a cast is usually to tell the compiler that you have some extra information - that you know something at compile time. You don't know that information here - you only know it at execution time.

What would you expect to do with the value after casting it? Admittedly there are some times when it would be useful - when you've got to use a generic interface, even if you want to get at members which don't require the type parameter (e.g. Count in IList<T>). However, if that's not what you're trying to do it would really help if you could give more information.

like image 103
Jon Skeet Avatar answered Oct 10 '22 09:10

Jon Skeet


I've just finished wrestling with this problem.
True, you cannot cast the object into a Generic IList but you can convert it into a strongly typed Array by invoking the "ToArray" method of the List object.

Solution pilfered from another blog. http://amazedsaint.blogspot.com/2008/04/creating-generic-list-at-runtime.html

ToArrayMethod = obj.GetType().GetMethod("ToArray");

System.Array stronglyTypedArray=(System.Array) ToArrayMethod.Invoke(obj,null);

like image 33
user23462 Avatar answered Oct 10 '22 09:10

user23462