Greetings!
I am trying to make it possible for new derived classes of an object to be
used by my application without rebuilding the application. The new classes
will be made known to my application by storing the file name, assembly name
and class name for them in a database. The code to create an instance of
the object will look something like the following:
Assembly asm = Assembly.LoadFrom(derivedFileName);
Type derivedType = asm.GetType(derivedTypeName);
bool argument = false;
object args = { argument };
object derivedObject = Activator.CreateInstance(derivedType, args);
BaseType base = (BaseType)derivedObject;
This code succeeds through the second-last line. derivedObject is created,
and the debug watch window shows it to be an object of type derivedType.
However, the last line fails with an invalid cast exception. If I create
derivedObject merely by:
object derivedObject = new derivedType();
then the cast to BaseType succeeds.
Why does the cast fail, and what can I do to use my derived object as though
it were a base object?
Thanks very much!
Rob
P.S. I can use use Activator.CreateInstance(string assemblyName, string
typeName), but that limits me to the default constructor. The only way I
found to use names instead of types was to use the fullest version of
CreateInstance(). But that version requires an array of at least one
ActivationAttribute object, and I could find no information at all on what
that is. The only examples I could find seemed to indicate that it was an
indication of the location of a remote object, and I don't want to activate
my object remotely.