Polymorphism in C#
# CHAPTER 16
Polymorphism in C#
1. Introduction
Polymorphism comes from Greek, meaning "many forms." In C#, it allows us to perform a single action in different ways. It is the magic that allows a video game engine to tell an array of 1,000 different entities toUpdate(), and each entity knows exactly how to update itself based on its specific class.
2. Learning Objectives
By the end of this chapter, you will be able to:- Define Polymorphism in OOP.
- Understand Compile-time Polymorphism (Method Overloading).
- Understand Runtime Polymorphism (Method Overriding).
- Use Base class variables to hold Derived class objects.
3. Types of Polymorphism
Polymorphism in C# takes two main forms:- 1. Compile-time Polymorphism (Static Binding): Achieved through Method Overloading. The compiler knows exactly which method to call when it builds the application.
-
2.
Runtime Polymorphism (Dynamic Binding): Achieved through Inheritance and Method Overriding (
virtual/override). The application decides which method to call *while it is running* based on the actual object type.
4. Compile-time Polymorphism (Recap)
We saw this in Chapter 11. It's when multiple methods have the same name but different parameters.5. Runtime Polymorphism (The Real Magic)
Let's look at the true power of OOP. A Base class variable is legally allowed to hold a Derived class object!6. Why is this useful?
Imagine a Drawing app. You have an abstract concept of aShape with a Draw() method. You have specific classes: Circle, Square, Triangle.
Without polymorphism, your code would look like:
if (type == "Circle") { drawCircle(); } else if (type == "Square") { drawSquare(); }
With polymorphism, you just put them all in a List<Shape> and loop through them calling shape.Draw(). If you add a Hexagon class later, you don't have to change the loop code at all! The system automatically scales.
7. OOP and Memory Explanation
How does the runtime know which method to call? C# uses a mechanism called the Virtual Method Table (VTable). When a class hasvirtual methods, the CLR creates a hidden table of function pointers. When myPet.Speak() is called, the CLR looks at the object in Heap memory, finds its VTable, and dynamically resolves the pointer to the Dog.Speak() method instead of the Animal.Speak() method.
8. Common Mistakes
-
Forgetting
override: If you forget theoverridekeyword in the child class (and optionally usenew), you perform Method Hiding. In this case,Animal myPet = new Dog(); myPet.Speak();will output "Animal sound", entirely defeating runtime polymorphism! Always useoverride.
9. Best Practices
-
Use polymorphism to eliminate massive
if/elseandswitchstatements that check an object's type.
10. Exercises
-
1.
Create a
Vehiclebase class with a virtualStartEngine()method.
-
2.
Create
CarandMotorcyclederived classes that overrideStartEngine().
-
3.
In
Main(), create an array ofVehiclecontaining both cars and motorcycles, and loop through them callingStartEngine().
11. MCQs with Answers
What does Polymorphism mean?
Method Overloading is an example of:
Method Overriding (virtual/override) is an example of:
BaseClass hold an object of type DerivedClass?
a) Yes (e.g., Animal a = new Dog();) b) No
Answer: a) Yes
Q5. Can a variable of type DerivedClass hold an object of type BaseClass?
a) Yes b) No (e.g., Dog d = new Animal(); is invalid)
Answer: b) No
What happens if you call a virtual method on a Base reference holding a Derived object?
What hidden structure does the CLR use to resolve virtual method calls at runtime?
What happens if you forget the override keyword in the derived class?
Polymorphism is excellent for eliminating which type of code?
12. Interview Questions
- Q: Differentiate between Compile-time and Runtime Polymorphism. Give examples of each.
- Q: Explain the "Liskov Substitution Principle" (The 'L' in SOLID) in the context of Polymorphism. (Answer: Objects of a superclass shall be replaceable with objects of its subclasses without breaking the application).
13. Summary
Polymorphism allows objects of different classes to be treated as objects of a common Base class. Through the power ofvirtual and override methods, the C# runtime dynamically ensures that the correct, specific behavior is executed, making your code highly scalable and maintainable.