Mendes
Mendes

Reputation: 18441

Using reflection cast returned data to list

I have the following classes:

public class MyExampleClass 
{
     public Prop1 { get; set; }
     public Prop2 { get; set; }
}

public MyExampleList
{
     public List<MyClass> { get; set; }
}

These are examples. I have several Classes and Lists with same structure.

Then a static class that will work on several types lists with the followin data:

public static WorkerClass
{
    public static List<T> GetListFromDb()
    {
         var list = new List<T>;

         ///  Do the job

         return list;
    }
}

Then I have reflection in another point of code, where I need to read this data:

public static class AnotherWorker
{
    public static class DoSomething()
    {
        Type typeToUse = Assembly.GetType("WorkerClass");   
        var methodToCall = typeToUse.GetType("GetListFromDb");

        object returnList = methodToCall.Invoke(null, null);

        ///
        /// 
        /// ?? Stuck here... how to foreach each list element and 
        /// dynamically store it in a new List<class_name>, being class_name a string, not a class.
        ///
        foreach (var item in returnList)
        { 
             .

        }

    }
}

How do I, using reflection, continue to handle that list dynamically, creating new objects and copying properties from one to another.

Thanks for help.

Upvotes: 1

Views: 1157

Answers (1)

dymanoid
dymanoid

Reputation: 15197

You cannot create an instance of a List<T> if T is unknown at compile time. That's the generics' purpose, actually: strong typing.

The foreach question is simple:

object returnList = methodToCall.Invoke(null, null);
IEnumerable enumerable = returnList as IEnumerable;
if (enumerable != null)
{
   foreach (var item in enumerable)
   {
       // do the job with each item...
   }
}

Update:

You can create another instance of the same List<T> type as your object like this:

Type listType = enumerable.GetType();
IList newList = Activator.CreateInstance(listType) as IList;
if (newList != null)
{
    foreach (var item in enumerable)
    {
        newList.Add(item);
    }
}

Upvotes: 1

Related Questions