Understanding and Implementing Polymorphism in C#: Compile-Time and Runtime Polymorphism
Explore polymorphism, a core concept of object-oriented programming (OOP) in C#. This tutorial explains compile-time polymorphism (method and operator overloading) and runtime polymorphism (method overriding), demonstrating how to create flexible and extensible object-oriented designs.
Understanding Polymorphism in C#
Polymorphism, meaning "many forms," is a powerful feature of object-oriented programming. It allows you to treat objects of different classes in a uniform way, based on a common interface or base class. C# supports two main types of polymorphism: compile-time and runtime polymorphism.
Compile-Time Polymorphism (Static Binding)
Compile-time polymorphism is determined at compile time. In C#, this is achieved through method overloading (having multiple methods with the same name but different parameters) and operator overloading (defining how operators work with custom types).
Runtime Polymorphism (Dynamic Binding)
Runtime polymorphism is determined at runtime. In C#, this is achieved through method overriding. Method overriding is when a derived class provides its own implementation of a method that's already defined in its base class.
Example 1: Method Overriding
public class Animal {
public virtual void MakeSound() { Console.WriteLine("Generic animal sound"); }
}
public class Dog : Animal {
public override void MakeSound() { Console.WriteLine("Woof!"); }
}
// ... (Main method to demonstrate) ...
Example 2: Multiple Derived Classes
public class Shape { public virtual void Draw() { } }
public class Circle : Shape { public override void Draw() { Console.WriteLine("Drawing a circle"); } }
public class Rectangle : Shape { public override void Draw() { Console.WriteLine("Drawing a rectangle"); } }
// ... (Main method to demonstrate) ...
Polymorphism and Data Members
Runtime polymorphism does *not* apply to data members (fields). The type of the reference variable, not the object's actual type, determines which field is accessed.
public class Animal { public string Color = "white"; }
public class Dog : Animal { public new string Color = "black"; }
// ... (Main method to demonstrate) ...