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 that shown here:

image

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

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.