How do I cast an object to its proper class at runtime given its System.Type
I have code that looks like this:
MyObject class has subclasses of MySubObjectA & MySubObjectB:
MyObject obja = new MySubObjectA ();
MyObject objb = new MySubObjectB ();
ArrayList list = new ArrayList();
list.Add(objb );
list.Add(obja );
ArrayList MyObjBs= GetAllOfType( typeof( MySubObjectB ) );
ArrayList MyObjAs = GetAllOfType( typeof( MySubObjectA ) );
public ArrayList GetAllOfType(System.Type t){
ArrayList result = new ArrayList();
foreach(object o in list){
Type objType = o.GetType();
if(objType.Equals(t))
result.Add( (t) o); //Doesn't compile
result.Add( o as t); //Doesn't compile
}
}
How do I get the objects properly casted to its class before I push em onto
my list? (I know that they are stored in the list as objects anyway, This
code isn't real, its purpose is only to express the question.)