I have this base class:
namespace DynamicGunsGallery
{
public class Module
{
protected string name;
public virtual string GetName() { return name; }
public virtual string GetInfo() { return null; }
}
}
And Im creating dynamic libraries that inherit from base class, e.g. (AK47.dll)
namespace DynamicGunsGallery
{
public class AK47 : Module
{
public AK47() { name = "AK47"; }
public override string GetInfo()
{
return @"The AK-47 is a selective-fire, gas-operated 7.62×39mm assault rifle, first developed in the USSR by Mikhail Kalashnikov.
It is officially known as Avtomat Kalashnikova . It is also known as a Kalashnikov, an AK, or in Russian slang, Kalash.";
}
}
}
I’m loading dynamic libraries using this (inspired by this link):
namespace DynamicGunsGallery
{
public static class ModulesManager
{
public static Module getInstance(String fileName)
{
/* Load in the assembly. */
Assembly moduleAssembly = Assembly.LoadFile(fileName);
/* Get the types of classes that are in this assembly. */
Type[] types = moduleAssembly.GetTypes();
/* Loop through the types in the assembly until we find
* a class that implements a Module.
*/
foreach (Type type in types)
{
if (type.BaseType.FullName == "DynamicGunsGallery.Module")
{
//
// Exception throwing on next line !
//
return (Module)Activator.CreateInstance(type);
}
}
return null;
}
}
}
I have included base class in both, my executable which contains ModuleManager and in dll library. I have no problem when compiling, but when I run this code I get an error:
InvalidCastException was unhandled.
Unable to cast object of type DynamicGunsGallery.AK47 to type
DynamicGunsGallery.Module
So the question is: Why cant I cast derivated class to base class?
Is there other way to load dynamic library and “control” it using methods from base class?
Going from your comments:
In your sub library, you can’t re-declare module; you must reference the module from the original library.
Add a reference to the main project from the project which has ak class in it.
I’d also think about changing the namespaces to make it obvious that you’ve got two libraries going on