Please help, I have a method that returns an Object. This returned object could be a generic list of 4 or more classes in my code. i.e the object could be List, List, List etc. At runtime when I recieve this object, I want to be able to cast it to a list of the appropriate type. PS. The methods return value is object. The writers of this class that I'm calling basically create a generic list and fill it up, then for reason i cant explain, they cast the list to an object and return is. The return line is exactly ==> return (object)thegeneicList How do I go about creating a generic list List where T is only known at runtime
| |
LB ElbinoPosted Nov 9, 2007, 10:38 PM
AlanPosted Nov 9, 2007, 12:13 PM
The method would only be able to have a return type of List if T were a type parameter of the method itself or of the class/struct of which the method were a member.
Otherwise, the only return type that can be used is 'object' because all generic List classes inherit directly from it. Moreover, two closed contructed generic classes, List and List, have no conversion relationship with each other even if A and B themselves do.
This also means that the only way you can cast the object to a List of the appropriate type is to consider each case individually. For example:
List list1 = null; list2 = null; list3 = null; list4 = null;
List
List
List
if (obj is List))obj;))obj;))obj;))obj;
list1 = (List
else if (obj is List
list2 = (List
else if (obj is List
list3 = (List
else if (obj is List
list4 = (List