C# Interview Question #17

What is polymorphism in C#?

OOP & Core C# Concepts Junior Beginner

Quick Interview Answer

Polymorphism allows code to work through a common type or contract while different concrete objects provide different behavior.

Detailed Explanation

Polymorphism allows code to work through a common type or contract while different concrete objects provide different behavior.

Compile-time polymorphism is commonly associated with method overloading. Runtime polymorphism is commonly achieved through virtual/override members or interface implementations.

This is important in production applications because code can depend on abstractions rather than concrete implementations.

Code Example

public class Animal
{
    public virtual void Speak() => Console.WriteLine("Animal sound");
}

public class Dog : Animal
{
    public override void Speak() => Console.WriteLine("Dog barks");
}

Animal animal = new Dog();
animal.Speak(); // Dog barks