Runtime cast down inheritance tree
-
Hi all. Casting problem here! If I have the following code:
Type classType = typeof(MyDerivedClass); MyBaseClass o = Activator.CreateInstance(classType) as MyBaseClass; ... o.SomeFunctionInDerivedClass();
This all works fine and splendid. But if I have this code in a function, and I want to, at runtime, decide on the type of class being instantiated, how do I do the 'as' keyword explicit cast? I'm using 1.1 so can't use templates/whatever they are called. TIA Gizz -
Hi all. Casting problem here! If I have the following code:
Type classType = typeof(MyDerivedClass); MyBaseClass o = Activator.CreateInstance(classType) as MyBaseClass; ... o.SomeFunctionInDerivedClass();
This all works fine and splendid. But if I have this code in a function, and I want to, at runtime, decide on the type of class being instantiated, how do I do the 'as' keyword explicit cast? I'm using 1.1 so can't use templates/whatever they are called. TIA GizzIf the type of the class is decided at runtime, then you can't have code like
o.SomeFunctionInDerivedClass();
either. What you'd have to do is use reflection to invoke methods, something like
object obj = Activator.CreateInstance(passedType);
obj.GetType().InvokeMember("SomeFunctionInDerivedClass",...);Of course, the type you instantiated might not have an "SomeFunctionInDerivedClass" method, it'll then result in an exception and you have to handle it. That's the price to pay for reflection, you lose compile time type safety. Regards Senthil _____________________________ My Blog | My Articles | WinMacro
-
Hi all. Casting problem here! If I have the following code:
Type classType = typeof(MyDerivedClass); MyBaseClass o = Activator.CreateInstance(classType) as MyBaseClass; ... o.SomeFunctionInDerivedClass();
This all works fine and splendid. But if I have this code in a function, and I want to, at runtime, decide on the type of class being instantiated, how do I do the 'as' keyword explicit cast? I'm using 1.1 so can't use templates/whatever they are called. TIA GizzYou don't need the as
MyBaseClass
at all because objects that are derived fromMyBaseClass
build on that class. SoMyBaseClass o = AnInstanceOfMyDerivedClass;
is acceptable.
My: Blog | Photos WDevs.com - Open Source Code Hosting, Blogs, FTP, Mail and More