• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 57
  • Last Modified:

Virtual Methods in .NET: The "is" keyword

I have an abstract class called Vehicle, and two child abstract classes called Car, and the other called Truck.

In the Vehicle class, I have a virtual method called TowTrailer(int weight). In this method in the Vehicle class, am I allowed to say:

if ( this is Car )
     return "Cars can't tow trailers."
else if ( this is Truck )
     return "Trucks can tow trailers."

I'm confused because on the one hand, since I'm creating the TowTrailer in the base class, it doesn't feel right to say if "this is Car". The answer is no. Vehicle is NOT a car, but a car is a vehicle.

However, since the TowTrailer method will be inherited by a child of either a Car or a Truck, this is perfectly fine, but I'm not sure.

Please let me know when it's OK to use the "is" keyword in a hierarchy. Thanks.
0
pzozulka
Asked:
pzozulka
1 Solution
 
käµfm³d 👽Commented:
In my opinion, you've got a bigger problem. The fact that you are checking for specific types of children in your base class means that you are designing your hiearchy incorrectly. You're introducing dependencies into your base class that will negatively impact maintainability. The whole point of virtual methods is that your base class doesn't care what the concrete type is; it only knows that the method is available.

The reason you use the is keyword is to test if an object can be converted to a certain type. Being able to be converted is based on the inheritance hierarchy. If you're designing your classes properly--which is tough at times--you shouldn't need the is keyword. In this case I think you've got a bad design. However, the usage of is appears correct.
0
 
louisfrCommented:
That method is virtual. You can then override it in each subclass to make the specific work.

In Car:
override string TowTrailer(int weight)
{
    return "Cars can't tow trailers.";
}

Open in new window


In Truck:
override string TowTrailer(int weight)
{
    return "Trucks can tow trailers."
}

Open in new window


And unless you have work to do in that method for any vehicle, make it abstract in the superclass.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now