David
David

Reputation: 2569

Casting object to generic IEnumerable with only type available

What is the correct code to cast an object back to a generic list like so?

Type x = typeof(MyClass);
object o = new List<MyClass>();

List<x> l = o as List<x>; // Not working

EDIT: Maybe it wasn't all clear: The object is a list of a generic type which i don't know at compile time.. nevertheless List has functions like "Add" i can call anyway, like:

l.Add((new MyClass() as object)) as x);

Upvotes: 1

Views: 1052

Answers (4)

abatishchev
abatishchev

Reputation: 100358

List<MyClass> l = (List<MyClass>)o;

or

List<MyClass> l = o as List<MyClass>;

Do you mean

List<> l = o as List<>;

This is not possible until you use a generic class:

class C<T>
{
    public List<T> List = new List<T>();
}

Usage:

C<MyClass> c = new C<MyClass>();
c.List.Add(new MyClass());

Finally I got OP's goal:

Type listType = typeof(List<>);
Type targetType = listType.MakeGenericType(typeof(YourClass));
List<YourClass> list = (List<YourClass>)Activator.CreateInstance(targetType);

See MSDN for details.

Upvotes: 2

user743382
user743382

Reputation:

When the generic interface is not usable because you don't know the type arguments at compile time, but a non-generic interface is available, you can use that instead:

Type x = typeof(MyClass);
object o = new List<MyClass>();

IList l = (IList)o;
l.Add(new MyClass());

The non-generic IList interface is implemented by the generic List<T> class.

Upvotes: 1

Dhanasekar Murugesan
Dhanasekar Murugesan

Reputation: 3239

        List<Employee> employees = new List<Employee> { new Employee { Id = Guid.NewGuid().ToString(), Name = "SOME" }, new Employee { Id = Guid.NewGuid().ToString(), Name = "SOME2" } };

        object obj = employees;

        List<Employee> unBoxed = (List<Employee>)obj;

Upvotes: 0

Jan
Jan

Reputation: 2168

object testobject = new List<string>();
List<string> list = (List<string>)testobject;

Upvotes: 0

Related Questions