C# Polymorphism
Many forms. Overriding methods.
C# Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit fields and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.
For example, think of a base class called Animal that has a method called animalSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds - and they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):
Method Overriding
To override a base class method, you must add the virtual keyword to the method in the base class, and use the override keyword for each derived class method:
Examples
Polymorphism Example
Different implementations of the same method.
using System;
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal // Derived class (child)
{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}No Override
Difference without virtual/override.
using System;
class Animal
{
public void sleep() { Console.WriteLine("Sleeping"); }
}
class Dog : Animal
{
// Hides the base method without override (warning)
public new void sleep() { Console.WriteLine("Dog Sleeping"); }
}
class Program
{
static void Main()
{
Animal a = new Dog();
a.sleep(); // Calls Animal's sleep because not virtual/override
Dog d = new Dog();
d.sleep(); // Calls Dog's sleep
}
}