Runtime Type casting

M

MattC

Hi,

How can do runtime casting?

MyCollection derives from ArrayList

I will store lost of different objects that all derive from the same parent
class. I then want to be able to pass in the object type and collection type
I have a number of classes that derive from ArrayList and have if pick out
on ly those i asked for.

Problem is it wont let me cast using a type as a method argument.

//public method in instance of MyCollection
public MyCollection GetTypesFromCollection(Type ObjectType, Type
CollectionType)
{

MyCollection s;
(CollectionType)s = new MyCollection(); //create collection and cast to
runtime collection type

foreach(object o in this) //loop through all entries in this arraylist
{
if(o.GetType() == ObjectType.GetType()) //if this object type is the
same as the type I'm asking for
{
s.Add( (ObjectType) o); //add it to the tryped arraylist
}
}
return s; //give it all back
}

Help!!
 
V

Violeta Dabnishka

Try this:

public MyCollection GetTypesFromCollection(Type ObjectType, Type
CollectionType)
{

MyCollection s = CollectionType.GetConstructor(null).Invoke() as
MyCollection; //create collection via reflection

foreach(object o in this) //loop through all entries in this arraylist
{
if(o.GetType() == ObjectType) //if this object type is the same as
the type I'm asking for
{
s.Add(o); //add it to the tryped arraylist
}
}
return s; //give it all back
}
 
N

Nick Malik

This is handled much more elegantly in C# 2.0 by using generics.

Until then, I suggest that you DON'T do this. The collection will still
contain strongly typed objects. Simply have the collection return the
object that is in it and, if you are concerned that the object isn't of the
right type, check it.

You can solve most of these problems using good patterns, without having to
force the collection type to a particular class.

I hope this helps,
--- Nick
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top