Hello,
I
just would like to know the best practice for dealing with this
situation in OOP, specifically C#. This is probably a very easy
question for seasoned OOP people, and I can think of a couple of ways I
could possibly do it, but I'm not sure what the best way to go is. So:
We have a base class eg 'Vehicle'.
This base class defines certain common properties and methods such as:
Weight
Height
RegistrationNumber
CalculateAge()
etc.
There are a number of derived classes that deal with specific types of vehicle, such as
Truck
Pickup
Car
Bus
etc.
Subclasses obv have their own properties and methods unique to the specific type of vehicle. Truck, for example might have:
MaxLoadWeight
IsArticulated
So my question is..
I
want to define a method where I can provide the RegistrationNumber of a
Vehicle of unknown type, and have an object returned to me which is of
the correct sub class. For example I want a Car object returned if the
RegistrationNumber I provide belongs to a car, and a truck object
returned if it belongs to a truck. What is the best way to do this?
Perhaps sub-classing isn't event the best approach. Maybe something interface based would be better? Any opinions??
Many Thanks!
S
Loading
Scott LyslePosted Dec 29, 2007, 12:53 AM
You could drop each item of any type into a collection and set the key to be equal to the registration number and the value side to hold the object itself. You could then search the collection to locate and return a specific object. You could then call GetType to find out what type of object it is. So, if you created a SortedList called sl and loaded each newly instanced object into that list, you could search it for a specific key using something like this:
private object GetObjectTypeByID(int iCaseNumber) { object o = null; // find the object by its ID and return the // object to the caller foreach (DictionaryEntry de in sl) { if ((int)de.Key == iRegistrationNumber) o = de.Value; } return o; }Once the object was returned you could process it differently by type using a switch statement. If you just wanted to get the type, something like this would give you that (but handle the prospects of getting a null object returned):
private void button1_Click(object sender, EventArgs e) { // get a copy of the object by its ID object o = GetObjectTypeByID(1); // display the type of object to the user MessageBox.Show(o.GetType().ToString()); }