How can polymorphism be implemented in C#?
In C#, polymorphism is typically achieved through inheritance and interfaces. The specific methods are as follows:
- Inheritance: By creating a parent class and multiple child classes, the child classes inherit the characteristics of the parent class and can override the parent class’s methods to achieve polymorphism. For example:
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog barks");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Cat meows");
}
}
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.MakeSound(); // Output: Dog barks
myCat.MakeSound(); // Output: Cat meows
- Interface: By defining an interface and then having multiple classes implement this interface, it allows for polymorphism of interface methods. For example:
interface IShape
{
double GetArea();
}
class Circle : IShape
{
public double Radius { get; set; }
public double GetArea()
{
return Math.PI * Radius * Radius;
}
}
class Rectangle : IShape
{
public double Width { get; set; }
public double Height { get; set; }
public double GetArea()
{
return Width * Height;
}
}
IShape myCircle = new Circle() { Radius = 5 };
IShape myRectangle = new Rectangle() { Width = 5, Height = 10 };
Console.WriteLine(myCircle.GetArea()); // Output: 78.54
Console.WriteLine(myRectangle.GetArea()); // Output: 50
By using these two methods, it is possible for objects of different classes to call the same method, achieving polymorphism.