Polymorphism is one of the four pillars of Object-Oriented Programming (OOP), along with encapsulation, inheritance, and abstraction. The term polymorphism comes from the Greek words "poly" (many) and "morph" (form), meaning many forms.
In C#, polymorphism allows objects of different classes related by inheritance to be treated as objects of a common base class. It enables a single interface to represent different underlying data types or classes.
In simple terms, polymorphism lets methods do different things based on the object they are acting upon, even though they share the same method name or interface.
C# supports two primary types of polymorphism:
Also called method overloading or operator overloading, this polymorphism is resolved during compile time.
Occurs when multiple methods have the same name but different parameters (number, types, or order).
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public double Add(double a, double b)
{
return a + b;
}
public int Add(int a, int b, int c)
{
return a + b + c;
}
}
class Program
{
static void Main()
{
Calculator calc = new Calculator();
Console.WriteLine(calc.Add(2, 3)); // Output: 5
Console.WriteLine(calc.Add(2.5, 3.5)); // Output: 6.0
Console.WriteLine(calc.Add(1, 2, 3)); // Output: 6
}
}
C# allows you to redefine or overload most built-in operators for your own classes or structs.
class Complex
{
public int Real { get; set; }
public int Imaginary { get; set; }
public Complex(int r, int i)
{
Real = r;
Imaginary = i;
}
// Overload + operator
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
public override string ToString()
{
return $"{Real} + {Imaginary}i";
}
}
class Program
{
static void Main()
{
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(3, 4);
Complex c3 = c1 + c2;
Console.WriteLine(c3); // Output: 4 + 6i
}
}
This is achieved through method overriding and is resolved during runtime using virtual methods and inheritance.
When a derived class provides a specific implementation of a method already defined in its base class.
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal sound");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Meow");
}
}
class Program
{
static void Main()
{
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
myAnimal.MakeSound(); // Output: Animal sound
myDog.MakeSound(); // Output: Bark
myCat.MakeSound(); // Output: Meow
}
}
Used in a base class to indicate that a method or property can be overridden in a derived class.
Used in a derived class to provide a new implementation of a virtual method or property declared in the base class.
Used to hide a member inherited from a base class with a new implementation. It is different from overriding and does not provide polymorphic behavior.
class BaseClass
{
public virtual void Display()
{
Console.WriteLine("Base Display");
}
public void Show()
{
Console.WriteLine("Base Show");
}
}
class DerivedClass : BaseClass
{
public override void Display()
{
Console.WriteLine("Derived Display");
}
public new void Show()
{
Console.WriteLine("Derived Show");
}
}
class Program
{
static void Main()
{
BaseClass obj1 = new DerivedClass();
obj1.Display(); // Calls Derived Display (polymorphism)
obj1.Show(); // Calls Base Show (no polymorphism)
DerivedClass obj2 = new DerivedClass();
obj2.Display(); // Derived Display
obj2.Show(); // Derived Show
}
}
Polymorphism is often implemented using abstract classes and interfaces, which define methods that derived classes must implement.
abstract class Shape
{
public abstract double GetArea();
}
class Circle : Shape
{
public double Radius { get; set; }
public Circle(double r) { Radius = r; }
public override double GetArea()
{
return Math.PI * Radius * Radius;
}
}
class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public Rectangle(double w, double h)
{
Width = w;
Height = h;
}
public override double GetArea()
{
return Width * Height;
}
}
class Program
{
static void Main()
{
Shape shape1 = new Circle(5);
Shape shape2 = new Rectangle(4, 6);
Console.WriteLine($"Circle Area: {shape1.GetArea()}"); // Output: Circle Area: 78.53981633974483
Console.WriteLine($"Rectangle Area: {shape2.GetArea()}"); // Output: Rectangle Area: 24
}
}
interface IVehicle
{
void Start();
}
class Car : IVehicle
{
public void Start()
{
Console.WriteLine("Car starting...");
}
}
class Bike : IVehicle
{
public void Start()
{
Console.WriteLine("Bike starting...");
}
}
class Program
{
static void Main()
{
IVehicle vehicle = new Car();
vehicle.Start(); // Output: Car starting...
vehicle = new Bike();
vehicle.Start(); // Output: Bike starting...
}
}
Many design patterns in software development rely heavily on polymorphism, including:
Polymorphism in C# empowers developers to write flexible, extensible, and maintainable code. By allowing objects to behave differently based on their actual types, polymorphism supports the design of robust systems that can grow and evolve without requiring significant rewrites.
Understanding both compile-time and runtime polymorphism, along with the use of virtual methods, overrides, interfaces, and abstract classes, is essential to mastering C# and object-oriented design.
Proper use of polymorphism simplifies code interaction, improves reusability, and facilitates implementation of advanced design patterns, making it a fundamental concept in professional software development.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved