Learn to Code via Tutorials on Repl.it!

← Back to all posts
Polymorphism tutorial c#
Bunnytoes (158)

Polymorphism c

we start by making a parents class Animal

class Animal
{
public virtual void MakeSound ()
{
Console.WriteLine("The animal makes a sound");
}
}

make sure to have this as a virtual void or it won't work
next we use the class animal we made and have pig be the child

class Pig : Animal  
{
  public override void MakeSound() 
  {
    Console.WriteLine("The pig says: oink oink");
  }
}

make sure this is override so that it can override the other thing. Repeat that with a different animal how many times you want.

class Dog : Animal  
{
  public override void MakeSound() 
  {
    Console.WriteLine("The dog says: woof woof");
  }
}
class Cat : Animal  
{
  public override void MakeSound() 
  {
    Console.WriteLine("The cat says: meow");
  }
}

now for the last part, we have the basic setup code

class Program 
{
  static void Main(string[] args) 
  {

then we make a Animal called what we want

Animal myAnimal = new Animal();  
    Animal myPig = new Pig();  
    Animal myDog = new Dog();  
    Animal myCat = new Cat();

    myAnimal.MakeSound();
    myPig.MakeSound();
    myDog.MakeSound();
    myCat.MakeSound();

the full code is

using System;



  class Animal  
{
  public virtual void MakeSound() 
  {
    Console.WriteLine("The animal makes a sound");
  }
}

class Pig : Animal  
{
  public override void MakeSound() 
  {
    Console.WriteLine("The pig says: oink oink");
  }
}

class Dog : Animal  
{
  public override void MakeSound() 
  {
    Console.WriteLine("The dog says: woof woof");
  }
}
class Cat : Animal  
{
  public override void MakeSound() 
  {
    Console.WriteLine("The cat says: meow");
  }
}

class Program 
{
  static void Main(string[] args) 
  {
    Animal myAnimal = new Animal();  
    Animal myPig = new Pig();  
    Animal myDog = new Dog();  
    Animal myCat = new Cat();

    myAnimal.MakeSound();
    myPig.MakeSound();
    myDog.MakeSound();
    myCat.MakeSound();
  }
}

and that's it! The output will be
The animal makes a sound
The pig says: oink oink
The dog says: woof woof
The cat says: meow

hope this was helpful and bye

Comments
hotnewtop
Highwayman (1483)

Is this a tutorial o for learning what polymorphism is or just how it's done in c#?

Bunnytoes (158)

@Highwayman it shows how it's done, because if you don't have the void as override it won't work, it shows you how to do it