0
0
C Sharp (C#)programming~10 mins

Why polymorphism matters in C Sharp (C#) - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a base class named Animal.

C Sharp (C#)
public class [1] {
    public void Speak() {
        Console.WriteLine("Animal sound");
    }
}
Drag options to blanks, or click blank then click option'
AAnimal
BDog
CCat
DBird
Attempts:
3 left
💡 Hint
Common Mistakes
Using a specific animal name like Dog or Cat for the base class.
2fill in blank
medium

Complete the code to override the Speak method in the Dog class.

C Sharp (C#)
public class Dog : Animal {
    public override void [1]() {
        Console.WriteLine("Bark");
    }
}
Drag options to blanks, or click blank then click option'
ASpeak
BRun
CEat
DSleep
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name that does not exist in the base class.
3fill in blank
hard

Fix the error in the code by completing the method declaration to allow polymorphism.

C Sharp (C#)
public class Animal {
    public [1] void Speak() {
        Console.WriteLine("Animal sound");
    }
}
Drag options to blanks, or click blank then click option'
Astatic
Babstract
Cvirtual
Dsealed
Attempts:
3 left
💡 Hint
Common Mistakes
Using static which prevents overriding.
Using sealed which prevents inheritance.
Using abstract without making the class abstract.
4fill in blank
hard

Fill both blanks to create a list of animals and call their Speak method polymorphically.

C Sharp (C#)
List<[1]> animals = new List<[2]> {
    new Dog(),
    new Cat()
};

foreach(var animal in animals) {
    animal.Speak();
}
Drag options to blanks, or click blank then click option'
AAnimal
BDog
CCat
Dobject
Attempts:
3 left
💡 Hint
Common Mistakes
Using a specific animal type like Dog or Cat for the list type.
5fill in blank
hard

Fill all three blanks to implement polymorphism with an interface and classes.

C Sharp (C#)
public interface I[1] {
    void Speak();
}

public class [2] : I[1] {
    public void Speak() {
        Console.WriteLine("Meow");
    }
}

I[1] animal = new [2]();
animal.Speak();
Drag options to blanks, or click blank then click option'
AAnimal
BCat
CDog
DPet
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching interface and class names.
Not using the interface type for the variable.