Junior — Middle
What language features of C# are used to implement polymorphism?
sobes.tech AI
Answer from AI
In C#, polymorphism is implemented using keywords and mechanisms that allow methods and properties to behave differently depending on the object's type at runtime. The main tools are:
- virtual — declares a method or property that can be overridden in a derived class.
- override — used in a derived class to override a virtual method of the base class.
- abstract — declares an abstract method or class that must be implemented in subclasses.
- interface — defines a contract that different classes can implement, providing polymorphic behavior.
Example:
public abstract class Animal
{
public abstract void Speak();
}
public class Dog : Animal
{
public override void Speak() => Console.WriteLine("Woof");
}
public class Cat : Animal
{
public override void Speak() => Console.WriteLine("Meow");
}
// Usage
Animal a = new Dog();
a.Speak(); // Outputs "Woof"
a = new Cat();
a.Speak(); // Outputs "Meow"
Thus, polymorphism allows working with objects through the base type, calling overridden methods of specific classes.