Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic List Replacement

Tags:

c#

list

generics

so I'm trying to set a list<> field within an object with a new list<>. this list could be of any type, hence the use of generics.

I get a compile time error, 'cannot convert System.Collections.Generic.List<object> expression to type System.Collections.Generic.IEnumerable<T>' Is there anyway to make this work?

private void MyGenericMethod<T>(FieldInfo field)
{   
    field.SetValue(obj, new List<T>(newObjectList));    // new List<T> allObjects.ConvertAll<IEnumerable>) ???
}
like image 308
user1229895 Avatar asked Nov 21 '25 11:11

user1229895


1 Answers

I'm with Damien. The problem must be newObjectList, because there's no problem passing a List of generic type to SetValue, as it accepts two arguments of type Object

public void SetValue(
Object obj,
Object value
)

If you create a new List and populate it with another collection, it will ask for a IEnumerable, so you should try something like

field.SetValue(obj, new List<T>(newObjectList as IEnumerable<T>));

At least, at compilation time, it will not throw any error

like image 165
Sergio Rosas Avatar answered Nov 24 '25 00:11

Sergio Rosas