O'Reilly logo

.NET Gotchas by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Inheritance and Polymorphism Gotchas

Though you can gain a superficial knowledge of C++ in a couple of weeks, and become adept at it in a few years, an experienced C++ programmer would probably never claim to be a master of the language. Its complexities are mind-boggling. (I know people who have made career changes because of it.) More recent languages have eliminated a number of its tricky features and made it much easier to write good code. However, they have their own set of challenges. While they have taken a few steps forward on a number of issues, they have gone a few steps backward on some others. This can impact the extensibility of your code, break polymorphism, and make it harder for you to derive from your classes. Learning what these challenges are, and avoiding them or handling them judiciously, is imperative to effective development. In this chapter I will discuss the things you need to be aware of in the areas of inheritance and polymorphism so you can make best use of these important concepts.

GOTCHA #42 Runtime Type Identification can hurt extensibility

In working with an inheritance hierarchy, how do you know which type an instance belongs to? Given a reference, you can use casting to convert it to the type you desire. However, the problem with casting is that if the conversion is not valid, it results in a runtime InvalidCastException. This is ugly and you must avoid it at all costs. What alternatives do you have?

.NET languages allow you to determine ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required