I'm trying to call from another assembly a base class static method from it's derived class dynamically, using the following code:
Assembly executingAssembly = Assembly.GetExecutingAssembly();
Assembly objectAssembly =
Assembly.Load(executingAssembly.GetReferencedAssemblies().
Where(a => a.Name == "WebDelightBLL").FirstOrDefault());
Type myType = objectAssembly.GetType("WebDelightBLL.Ingredient");
MethodInfo myMethod = myType.GetMethod("GetAll", BindingFlags.Public | BindingFlags.Static);
object myInstance = Activator.CreateInstance(myType);
dgvResultsRES.DataSource = myMethod.Invoke(myInstance, null);
Code in the Dll as following:
public class BaseClass<DerivedClass>
{
public static Type MyType()
{
return typeof(DerivedClass);
}
public static string Prefix()
{
return "Sp" + MyType().Name;
}
public static DataTable GetAll()
{
try
{
DataTable dt = GetSP(Connection.connectionString(),
Prefix() + "GetAll", 5);
return dt;
}
catch (Exception)
{
throw;
}
}
}
public class Ingredient : BaseClass<Ingredient>
{
public string SayHello()
{
return "Hello, World!"; //Just to exemplify a point
}
}
But I always get "Object reference not set to an instance of an object"
If I try to call 'SayHello()' for instance I get no error.
Is this even possible?
Update:
By adding BindingFlags.FlattenHierarchy as indicated by Creep it worked like a charm. Working code as follows:
Type myType = objectAssembly.GetType("WebDelightBLL.Ingredient");
MethodInfo myMethod = myType.GetMethod("GetAll", BindingFlags.Public
| BindingFlags.Static | BindingFlags.FlattenHierarchy);
//object myInstance = Activator.CreateInstance(myType); <-- not needed.
dgvResultsRES.DataSource = myMethod.Invoke(null, null);
Since your method is static in your base class, it does not belong to its child.
The following code will work: