Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

C# Polymorphism:


Polymorphism is a concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass. It enables you to invoke methods on objects without knowing their specific type, making your code more flexible and reusable.

Here's a simple explanation with an example:

Let's say we have a superclass called Shape with a method Draw(). We also have two subclasses: Circle and Rectangle, both of which override the Draw() method to draw themselves in a different way.

Example

using System;

// Superclass
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}

// Subclass 1
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}

// Subclass 2
class Rectangle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a rectangle");
}
}

class Program
{
static void Main(string[] args)
{
Shape[] shapes = new Shape[2];
shapes[0] = new Circle();
shapes[1] = new Rectangle();

// Polymorphic method call
foreach (Shape shape in shapes)
{
shape.Draw();
}
}
}

In this example:

Polymorphism allows us to treat objects of different classes in a uniform manner, which promotes code flexibility and reusability.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java