I was feeling quite clever as I worked out how to create subclasses in C# for an ASP.NET project, then I found a problem – I didn’t know how to create an object of the right subclass based on the results of a SQL query.
Say you have a class called Animal and two subclasses called Zebra and Elephant. You get the idea?
What I want to do is perform a SQL query and if the row returned has row[“Type”]=”Zebra” then load a Zebra object (or if it’s an Elephant then..).
So, in principle, the Animal class would have a static method:
class Animal{
public static Animal Load(DataRow row){
if (row["Type"]=="Zebra"){
return new Zebra();
}
}
class Zebra : Animal{
//some code here
}
Is this at all possible or have I just plain got the idea of subclasses wrong. It should be obvious I’m no OO expert.
Thanks in advance,
Jake
You can implement the method factory pattern.
http://en.wikipedia.org/wiki/Factory_method_pattern