Practical 7: Polymorphism

CAB201 - Programming Principles

School of Computer Science, Faculty of Science

Polymorphism in C#

Polymorphism allows a method to do different things based on the object it is acting upon. In C#, polymorphism is achieved through:

  • Method overriding: A method in a derived class with the same signature as a method in the base class.
  • Method overloading: Multiple methods with the same name but different parameters in the same class.
CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Method Overriding - Dynamic Binding

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Grrr");
    }
}
public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof");
    }
}
public class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Meow");
    }
}
Animal unknownAnimal = new Animal();
Animal dog = new Dog();
Animal cat = new Cat();
unknownAnimal.MakeSound(); // Grrr
dog.MakeSound(); // Woof
cat.MakeSound(); // Meow
CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Method Overloading

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }
    public int Add(int a, int b, int c)
    {
        return a + b + c;
    }
    public double Add(double a, double b)
    {
        return a + b;
    }
}

Depending on the number and type of arguments, the correct method is called, despite having the same name.

Calculator calc = new Calculator();
calc.Add(1, 2); // 3
calc.Add(1, 2, 3); // 6
calc.Add(1.5, 2.5); // 4.0
CAB201 - Programming Principles
School of Computer Science, Faculty of Science