C# Polymorphism

What is Polymorphism?

Polymorphism means "many forms." It allows the same method to behave differently depending on the object using it.

It is a key concept in object-oriented programming and works closely with inheritance.

Loading...
Output:

Method Overriding (Runtime Polymorphism)

Method overriding allows a child class to provide a different implementation of a method from the parent class.

The parent method must use virtual, and the child uses override.

Loading...
Output:

Using Parent References

You can use a parent class reference to point to a child object.

The method that runs depends on the actual object type, not the reference type.

Loading...
Output:

Method Overloading (Compile-Time Polymorphism)

Method overloading allows multiple methods with the same name but different parameters.

The compiler decides which method to call based on the arguments.

Loading...
Output:

Runtime vs Compile-Time

Overriding is resolved at runtime based on the object's type.

Overloading is resolved at compile time based on method parameters.

Loading...
Output:

Why Use Polymorphism?

Polymorphism allows you to write flexible and reusable code.

  • Reduces code duplication
  • Improves scalability
  • Allows working with general types

Real-World Example

Different objects can respond differently to the same method call.

Loading...
Output:

Practice

Create a Shape class with a Draw() method. Then create Circle and Rectangle classes that override it.

Loading...
Output:

Need Help?