O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

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 and Virtual Members

Now that you know how to derive a class and call members on the base class, we’re ready to introduce another pillar of OOP: polymorphism. In passing, we’ve already seen how an instance of a subclass can be used in a place where a less-derived type is expected. This enables code such as the fragment shown here:

string s = "Hello";object o = s;

Because every string is an object, we can do this assignment. Where things get interesting is when we try to invoke a method on o. In particular, what should happen if we call, say, the ToString method:

Console.WriteLine(o.ToString());

Who’s responsible for creating a suitable ToString method that will provide meaningful output? In this particular case, we happen to know ...

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