Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Object to Generic List

Tags:

c#

list

generics

I have 3 generict type list.

List<Contact> = new List<Contact>();
List<Address> = new List<Address>();
List<Document> = new List<Document>();

And save it on a variable with type object. Now i nedd do Cast Back to List to perfom a foreach, some like this:

List<Contact> = (List<Contact>)obj;

But obj content change every time, and i have some like this:

List<???> = (List<???>)obj;

I have another variable holding current obj Type:

Type t = typeof(obj);

Can i do some thing like that??:

List<t> = (List<t>)obj;

Obs: I no the current type in the list but i need to cast , and i dont now another form instead:

List<Contact> = new List<Contact>();
like image 358
JoeLoco Avatar asked May 14 '10 19:05

JoeLoco


People also ask

Can you cast generic type java?

The Java compiler won't let you cast a generic type across its type parameters because the target type, in general, is neither a subtype nor a supertype.

What is generic list in C#?

The Generic List<T> Class in C# is a collection class that is present in System. Collections. Generic namespace. This Generic List<T> Collection Class represents a strongly typed list of objects which can be accessed by using the index.


1 Answers

Lots of trial and error gave me this on SL 5 but it should also work on a regular C#. You also need to add LINQ to your using list for the last half to work.

    List<object> myAnythingList = (value as IEnumerable<object>).Cast<object>().ToList()

Enjoy!

like image 144
Andrew Marais Avatar answered Sep 21 '22 16:09

Andrew Marais