Polymorphism in C# Language
Polymorphism is a fundamental concept in object-oriented programming, and it plays a crucial role in the
"_blank" rel="noopener">C# language. It allows objects of different types to be treated as if they belong to a common base type. This flexibility is one of the key features that make C# a powerful and expressive programming language.Polymorphism is primarily achieved through two mechanisms in C#: method overriding and interfaces. Let’s explore each of these mechanisms with examples.
Method Overriding
Method overriding allows a derived class to provide a specific implementation of a method that is already defined in its base class. This enables you to create different behavior for objects of the same base class.
Here’s an example of method overriding in C#:
using System;
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
class Square : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a square");
}
}
class Program
{
static void Main()
{
Shape shape1 = new Circle();
Shape shape2 = new Square();
shape1.Draw(); // Output: Drawing a circle
shape2.Draw(); // Output: Drawing a square
}
}
In this example, we have a base class Shape with a virtual Draw method, and two derived classes, Circle and Square, which override the Draw method with their own implementations. When we create instances of these derived classes and call the Draw method through a reference of the base class, the appropriate overridden method is called, demonstrating polymorphism.
Interfaces
Another way to achieve polymorphism in C# is by using interfaces. An interface defines a contract for a set of methods, and classes that implement the interface must provide concrete implementations for those methods. This allows objects of different classes to be treated as if they share a common interface.
Here’s an example of polymorphism using interfaces:
using System;
interface IDrawable
{
void Draw();
}
class Circle : IDrawable
{
public void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
class Square : IDrawable
{
public void Draw()
{
Console.WriteLine("Drawing a square");
}
}
class Program
{
static void Main()
{
IDrawable shape1 = new Circle();
IDrawable shape2 = new Square();
shape1.Draw(); // Output: Drawing a circle
shape2.Draw(); // Output: Drawing a square
}
}
In this example, we define an IDrawable interface with a Draw method, and both Circle and Square classes implement this interface. Objects of different classes can be treated as IDrawable, allowing polymorphism.
Discover more from PiEmbSysTech - Embedded Systems & VLSI Lab
Subscribe to get the latest posts sent to your email.



