I've created an abstract class, lets call it FooBarizable
, that is the parent of 2 clases(more in the practice), Foo
and Bar
. Now, I have a FooBarizableManager
that manages Foo
and Bar
classes, depending on his type. And from this FroobarizableManager
, I want to call getFooBarizables()
. Let's see the structure:
FooBarizable.cs:
public abstract class FooBarizable{
public string Name { get; set; }
public static IEnumerable<FooBarizable> GetFooBars(){
throw new NotImplementedException();
}
}
Foo.cs:
public class Foo : FooBarizable{
public static IEnumerable<FooBarizable> GetFooBars(){
return API.getFoos();
}
}
Bar.cs:
public class Bar : FooBarizable{
public static IEnumerable<FooBarizable> GetFooBars(){
return API.getBars();
}
}
FooBarizableManager.cs:
public class FooBarizableManager {
private Type type;
public FooBarizableManager(Type _t){
this.type = _t;
}
public void showFooBarizables(){
MethodInfo method = type.GetMethod("GetFooBars");
IEnumerable<FooBarizable> FooBars = (IEnumerable<FooBarizable>)method.invoke(null, null);
show(FooBars);
}
...
}
So, my problem is that I want to get the object collection from the manager, using the type, but enforce child classes to implement getFooBars()
method.
Problems I've faced:
.Net does not allow to define static abstract methods, so I cannot create
public static abstract IEnumerable<FooBarizable> GetFooBars()
and enforce child class to implement it.The way that is implemented does not enforce the implementation of the method in child classes, but I try to at least throw a
NotImplementedException
. The problem is that when I callMethodInfo method = type.GetMethod("GetFooBars");
in the manager, if the subclase does not implements the method,method
is null, andNullPointerException
is called instead.I've tried to create an instance method instead of static a static one, it solves the enforce problem because child classes have to implement it, But it does not seem correct to me to create an unnecessary instance to call a method.
So, is there any solution to enforce child classes to implement getFooBar()
method? if not, how can I throw the NotImplementedException
instead of NullPointerException
?