Just have a quick question… any help would be greatly appreciate!
I’m writing a database. I have a class called “Mechanism” which is inherited by two other classes called “motorcycle” and “automobile.” How would i go about printing the contents of motorcycle or automobile – depending on what the user has decided to enter into the database?
this is what i have so far, it’s giving me this error: InvalidCastException was unhandled. Unable to cast object of type “ConsoleApplication1.Automobile” to type “ConsoleApplication1.Motorcycle”
foreach (Mechanism m in mechanisms)
{
//ptr = m;
if (flagAuto == true)
{
Mechanism ptr = null;
ptr = m;
Console.WriteLine("ptr = " + ptr);
Console.WriteLine("ptr2 = " + ptr2);
ptr2 = (Automobile)ptr;
Console.WriteLine("inside Auto");
ofp.WriteLine("" + (ptr2.getManufacturer()));
ofp.WriteLine("" + ptr2.getModel());
ofp.WriteLine("" + ptr2.getModelYear());
ofp.WriteLine("" + ptr2.getVIN());
ofp.WriteLine("" + ptr2.getInitialPurchasePrice());
ofp.WriteLine("" + ptr2.getPurchaseDate());
ofp.WriteLine("" + ptr2.getSizeOfEngine());
ofp.WriteLine("" + ptr2.getTypeOfFuel());
ofp.WriteLine("" + ptr2.getNumberOfDoors());
ptr2 = null;
ptr = null;
Console.WriteLine("finishinge Auto");
}
else if (flagMotor == true)
{
Mechanism ptr = null;
ptr = m;
Console.WriteLine("ptr = " + ptr);
Console.WriteLine("ptr2 = " + ptr1);
Console.WriteLine("inside Motor");
ptr1 = (Motorcycle)ptr;
ofp.WriteLine("" + ptr1.getManufacturer());
ofp.WriteLine("" + ptr1.getModel());
ofp.WriteLine("" + ptr1.getModelYear());
ofp.WriteLine("" + ptr1.getVIN());
ofp.WriteLine("" + ptr1.getInitialPurchasePrice());
ofp.WriteLine("" + ptr1.getPurchaseDate());
ofp.WriteLine("" + ptr1.getSizeOfEngine());
ofp.WriteLine("" + ptr1.getTypeOfMotorcycle());
ptr1 = null;
ptr = null;
Console.WriteLine("finishing Motor");
}
the flags are supposed to keep track of which type of vehicle is trying to be entered into my database – then it should write it out to a text file..
That means the value of the flag is wrong.
You should do this instead:
By the way, you’re doing the same thing in the both branch. That implies, that you could implement them in a base class (
Mechanism), call those methods onmobject.