tags:

views:

72

answers:

4

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>();

Help Plz!!!

+1  A: 

A general solution like this (to instantiate a type with a generic parameter based on a System.Type object) is not possible. If you're really just dealing with these three types, though, then you're in luck because it's pretty easy:

Type t = typeof(obj);

if (t == typeof(List<Contact>)) {
    var contactList = (List<Contact>)obj;
    // do stuff with contactList

} else if (t == typeof(List<Address>)) {
    var addressList = (List<Address>)obj;
    // do stuff with addressList

} else if (t == typeof(List<Document>)) {
    var documentList = (List<Document>)obj;
    // do stuff with documentList
}
Dan Tao
in the future i need more objects, dont work thank´s!!
CrazyJoe
+2  A: 

What a sticky problem. Try this:

List<Contact> c = null;
List<Address> a = null;
List<Document> d = null;

object o = GetObject();

c = o as List<Contact>;
a = o as List<Address>;
d = o as List<Document>;

Between c, a, and d, there's 2 nulls and 1 non-null, or 3 nulls.


Take 2:

object o = GetObject();
IEnumerable e = o as IEnumerable;
IEnumerable<Contact> c = e.OfType<Contact>();
IEnumerable<Address> a = e.OfType<Address>();
IEnumerable<Document> d = e.OfType<Document>();
David B
in the future i need more objects, dont work thank´s!!
CrazyJoe
it work man, 7 hours, thanks a lottttttttttttttt!!!!!!
CrazyJoe
A: 

You might need to do the following:

if(object is List) { list = (List)object }

dominic
not really, no.
Femaref
List require a type, dont work thank's!!
CrazyJoe
A: 

No, you can't cast without going around corners (this is: reflection), generic type parameters have to be known at compile time. You can of course do something like this:

content.Where(o => o is type).ToList().Foreach(stuff);

Femaref