In the example below, how can I get SpecialThingDB to return a List of SpecialThings without having to re-implement all of ThingDB’s methods as I have done?
public class Thing
{
public readonly string Color;
public readonly int Weight;
public Thing(string color, int weight)
{
Color = color;
Weight = weight;
}
// Some methods
}
public class ThingDB
{
public List<Thing> GetByColor(string color)
{
var things = new List<Thing>();
// Get things from the database's Thing table
return things;
}
public List<Thing> GetByWeight(int weight)
{
var things = new List<Thing>();
// Get things from the database's Thing table
return things;
}
}
public class SpecialThing : Thing
{
public SpecialThing(string color, int weight) : base(color, weight)
{
}
// Some special methods
}
public class SpecialThingDB : ThingDB
{
// How do I have GetByColor and GetByWeight return SpecialThings here
// without completely re-implementing the base methods like below?
public List<SpecialThing> GetByColor(string color)
{
var specialThings = new List<SpecialThing>();
// Get things from the database's Thing table
return specialThings;
}
public List<SpecialThing> GetByWeight(int weight)
{
var specialThings = new List<SpecialThing>();
// Get things from the database's Thing table
return specialThings;
}
}
Also, is there a better pattern other than having two classes (one representing one record and the other being a manager class) for every table in my database?
UPDATE
Given the solution (thanks, the_joric!), here is what I’ve changed about the above code:
public class ThingDB<T> where T : Thing
{
public List<T> GetByColor(string color)
{
var things = new List<T>();
// Do some database stuff to fill things by color
return things;
}
public List<T> GetByWeight(int weight)
{
var things = new List<T>();
// Do some database stuff to fill things by weight
return things;
}
}
public class SpecialThing : Thing
{
public SpecialThing(string color, int weight)
: base(color, weight)
{
}
// Some special methods
}
public class SpecialThingDB : ThingDB<SpecialThing> { }
public class ThingDB : ThingDB<Thing> { } // For backward-compatibility
You can use generics. Like the following: