I am new to programming with OOP, I am trying to properly use the concept of inheritance.
Here is the code here is what I tried (Link Here)
public class Base
{
//Type?
public abstract static object Adapter();
public static DataTable GetWOCost(DateTime Date, string WO)
{
Application.UseWaitCursor = true;
DataTable dt = new DataTable();
try
{
//Cast?
dt = Adapter().GetDataByWO(WO, Date);
Application.UseWaitCursor = false;
return dt;
} catch (Exception)
{
return null;
}
}
}
public class Materiel : Base
{
static AllieesDBTableAdapters.CoutMatTableAdapter Adapter()
{
return new AllieesDBTableAdapters.CoutMatTableAdapter();
}
}
public class Labor : Base
{
static AllieesDBTableAdapters.CoutLaborTableAdapter Adapter()
{
return new AllieesDBTableAdapters.CoutLaborTableAdapter();
}
}
At first all of my code was in the Material class. But I then had to add a second identical class, but for a different SQL adapter. I tried different things, but the above code has a big problem.
Since the type is changing I used object, but it will not work without a cast. But since I cannot know what type it will be, what is the proper way for having 2 or more class that has the methods GetWOCost, but with different adapters?
Maybe I should change to .NET 4.0 and use a dynamic object?
edit: Also there seems to have a problem with abstract and static, so I cannot use the static modifier on my Method GetWOCost() without having an instance of Adapter() (in the base class). It seems it would be easier to just copy-paste, but I am trying to figure out the proper way to do it.
What you should do in this kind of situation, is to program against an interface, which defines the contract for what you want to do with the Adapter object. If your implementation classes do not share a common interface, you can create one for them.
Then you can create different implementations of this interface; and in each subclass override the adapter method to return the correct interface implementation.
You should get rid of your static methods, since the whole idea of polymorphic types is that you can get different instances that does the same thing, but in different ways.
In code, this might look like this (simplified):
Then you just need to have your different adapters implement your new interface, such as: