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 ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.