O'Reilly logo

Learning C# 3.0 by Brian MacDonald, Jesse Liberty

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

Polymorphism

There are two powerful aspects to inheritance. One is code reuse. When you create a ListBox class, you're able to reuse some of the logic in the base (Control) class.

What is arguably more powerful, however, is the second aspect of inheritance: polymorphism. Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details.

When the phone company sends your phone a ring signal, it does not know what type of phone is on the other end of the line. You might have an old-fashioned Western Electric phone that energizes a motor to ring a bell, or you might have an electronic phone that plays digital music.

As far as the phone company is concerned, it knows only about the "base type" phone and expects that any "derived" instance of this type knows how to ring. When the phone company tells your phone to ring, it, effectively, calls your phone's ring method, and old-fashioned phones ring, digital phones trill, and cutting-edge phones announce your name. The phone company doesn't know or care what your individual phone does; it treats your telephone polymorphically.

Creating Polymorphic Types

Because a ListBox is a Control and a Button is a Control, you expect to be able to use either of these types in situations that call for a Control. For example, a form might want to keep a collection of all the derived instances of Control it manages (buttons, lists, and so on) so that when the form is opened, it can tell each ...

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