Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a List<unknown type at compile time> and copy items via System.Reflection.PropertyInfo

I have come across something pretty complex. I would be obliged if anyone can help.

1) I have to create a List<> of unknown type at compile time. That I have already achieved.

 Type customList = typeof(List<>).MakeGenericType(tempType);
 object objectList = (List<object>)Activator.CreateInstance(customList);

"temptype" is the custom type thats been already fetched.

2) Now I have PropertyInfo object which is that list from which I have to copy all items to the the instance that I have just created "objectList"

3) Then I need to iterate and access the items of "objectList" as if it were a "System.Generic.List".

Cutting long story short, using reflection I need to extract a property that is a list and have it as an instance for further use. Your suggestions would be appreciated. Thanks in Advance.

Umair

like image 930
Omayr Avatar asked Feb 03 '26 13:02

Omayr


1 Answers

Many of the .NET generic collection classes also implement their non-generic interfaces. I'd make use of these to write your code.

// Create a List<> of unknown type at compile time.
Type customList = typeof(List<>).MakeGenericType(tempType);
IList objectList = (IList)Activator.CreateInstance(customList);

// Copy items from a PropertyInfo list to the object just created
object o = objectThatContainsListToCopyFrom;
PropertyInfo p = o.GetType().GetProperty("PropertyName");
IEnumerable copyFrom = p.GetValue(o, null);
foreach(object item in copyFrom) objectList.Add(item); // Will throw exceptions if the types don't match.

// Iterate and access the items of "objectList"
// (objectList declared above as non-generic IEnumerable)
foreach(object item in objectList) { Debug.WriteLine(item.ToString()); }
like image 87
David Yaw Avatar answered Feb 06 '26 03:02

David Yaw