Hi,
I have a table which houses two entities, StaticProgram and DynamicProgram. There is one column in that table called ProgramType which determines if a program is of type "Static" or "Dynamic". Though these two entities are stored in one table (I am guessing because the primitive fields for Static and Dynamic programs are exactly the same) but from a business point of view these are two VERY different entities.
So, I created two classes StaticProgram and DynamicProgram. However, I donot want to create two seperate Data Access Classes because it is going to be the exact same code replicated twice. I tried creating a "Program" class as base class and inherited StaticProgram and DynamicProgram classes but down casting is not supported so I can't return a "Program" object from the data access class and cast it to "StaticProgram" class etc.
So, what are my options? Can I create an IProgram interface and have StaticProgram and DynamicProgram implement that interface and have my Data Access class return IProgram? Or what about making the Data Access method a Generic method (if this is possible and is a recommended approach I will need some help as I do not have much expreience with generics)? Any other suggestions?
I would appreciate your help!!
Update: The data access method is static indeed:
public static class ProgramDataMapper
{
public static Program GetProgram(int programID)
{
Program p = new Program();
// database stuff
p.Name = reader["Name"].ToString();
...
return p;
}
}
Base class looks like:
public class Program
{
// Properties
public static Program GetProgram(int programID)
{
return ProgramDataMapper.GetProgram(programID);
}
}
Finally the derived class:
public class DynamicProgram : Program
{
// Additional Business Related Properties
public new static DynamicProgram GetProgram(int programID)
{
return (DynamicProgram)Program.GetProgram(programID);
}
}
This compiles just fine but I get a Cannot cast "Program" to "DynamicProgram" exception at runtime.
Also, what about a generic method? Unless I am off the mark here but, theoratically, can we not do something like:
public static IProgram GetProgram<T>(int programID) where T : IProgram
{
IProgram program;
Type returnType = typeof(T);
if(returnType is StaticProgram)
{
program = new StaticProgram();
}
else if(returnType = DynamicProgram)
{
program = new DynamicProgram();
}
//if (T is StaticProgram)
//{
// returnValue = new StaticProgram();
//}
//else if (T is DynamicProgram)
//{
// returnValue = new DynamicProgram();
//}
// db operations
}
Of course the code above doesn't work. I get "The given expression is never of the provided type (StaticProgram) type."