We help IT Professionals succeed at work.
Get Started

Virtual Methods in .NET: The "is" keyword

pzozulka
pzozulka asked
on
98 Views
Last Modified: 2015-03-15
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.
Comment
Watch Question
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE