sanitizedUser
sanitizedUser

Reputation: 2115

How to get List<int> from System.Object retrieved by reflection?

As suggested by @John, here is re-write:

Consider this code:

public object Foo(object original)
{
    List<object> origList = original as List<object>;    //problematic line, origList is null even though it was initialized as [1,2,3] in main method
    List<object> copy = new List<object>();

    foreach (var item in origList)
        copy.Add(item);

    return copy;
}

class Example
{
    List<int> someList = new List<int>() { 1,2,3 };
    // and also other Lists, I dont know their type at compile time
    // and other fields and methods
}

//in usage method:

Example e1 = new Example();
object obj1 = e1;    // this is original
Example e2 = new Example();
object obj2 = e2;   // this is copy

FieldInfo[] fields_of_class = obj1.GetType().GetFields(
            BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

foreach(FieldInfo fi in fields_of_class)
{
    object currentObject = fi.GetValue(obj1);

    // do type checking
    if (IsList(currentObject)
    {
        fi.SetValue(obj2, Foo(currentObject));    // here I have to retrive copy of the list, but I dont know generic argument beforehand as it can be List<insert any type here>
    }
}

How can I get that original list from System.Object in Foo method?

Preferably, I would like not to use generic methods as I would have to MakeGenericMethod which is slow for me. But if that's only solution I take it.

Now I know this isn't the smallest code example. Right now, I am looking into some other solutions of the problem.

Upvotes: -1

Views: 232

Answers (1)

user12031933
user12031933

Reputation:

You can try this:

public object Foo(object original)
{
  if ( original is System.Collections.IEnumerable )
  {
    List<object> copy = new List<object>();

    foreach ( var item in original as System.Collections.IEnumerable )
      copy.Add(item);

    return copy;
  }
  else
    return null;
}

Upvotes: 1

Related Questions