Click to See Complete Forum and Search --> : Type-casting by type.


CyberRascal
September 16th, 2008, 01:30 PM
Hey.

I have a List<DataModel> called object. At run-time I do not know what type this DataModel is, only that is derives from Model. Now, I must do a for-each loop on the elements in this list. I cannot simply cast it by the following example:



object = new List<DataModel>();
List<Model> models = (List<Model>)object;



Is it possible to somehow perform a for-each loop or cast the list<DataModel> to a List<Model>?

It would be great if there was a method similar to Array.CreateInstance(Type type), which creates an array of a specified Type, but that converted each item in a list to the specified Type.

There is an extension method called Cast, which is used to cast the current list to another type T, which would be fine, as I know I want to convert it to Model, but I can't use that method since I can't cast List<DataModel> to a List since the List needs a type definition. Any tips?

CyberRascal
September 16th, 2008, 03:02 PM
Hello. I found the solution to my problem on my own. Seems there were many solutions, one of them casting to interface IList which provides access to an enumerator without having to declare the type of objects in the list.

Thanks.

JonnyPoet
September 16th, 2008, 03:18 PM
Hello. I found the solution to my problem on my own. Seems there were many solutions, one of them casting to interface IList which provides access to an enumerator without having to declare the type of objects in the list.

Thanks.Yes there are maybe many solutions, but I want to acknowledge this as IMHO this is one of the best solutions for your problems :wave: especially when working with patterns and models. Basically said I would say always prefer interfaces over inheritance.

CyberRascal
September 16th, 2008, 04:15 PM
Hey, thanks for answering :)

I just had another follow-up question. It's not really relevant in my project, but IList does not provide access to methods like Find, Sort or other useful stuff like that. Is there any way to access these methods without at compile-time knowing the type?

Thank you :)

Mutant_Fruit
September 16th, 2008, 09:14 PM
The best way would be to instantiate a List<Model> to start off with rather than a List<DataModel> if that's possible.

boudino
September 17th, 2008, 02:16 AM
Following doesn't work?

List<DataModel>() dataModels = new List<DataModel>();
foreach (Model e in dataModels)
{
// do something
}


Generally, if you are facing working with type unknown at runtime, I would recommend you to focus on interfaces and go the way of "desing by contract".