Recall & Review
beginner
What does the
virtual keyword do in C#?The <code>virtual</code> keyword allows a method in a base class to be overridden in a derived class. It marks the method as extendable or replaceable.Click to reveal answer
beginner
What is the purpose of the
override keyword in C#?The <code>override</code> keyword tells the compiler that a method in a derived class is replacing a <code>virtual</code> method from its base class.Click to reveal answer
intermediate
Can a method without <code>virtual</code> in the base class be overridden with <code>override</code> in the derived class?No. Only methods marked <code>virtual</code> (or <code>abstract</code>) in the base class can be overridden using <code>override</code> in the derived class.Click to reveal answer
intermediate
What happens if you call a virtual method on a base class reference that points to a derived class object?The overridden method in the derived class is called. This is called polymorphism and allows behavior to change based on the actual object type.Click to reveal answer
beginner
Show a simple example of method overriding using
virtual and override.Example:<br><pre>class Animal {
public virtual void Speak() {
Console.WriteLine("Animal speaks");
}
}
class Dog : Animal {
public override void Speak() {
Console.WriteLine("Dog barks");
}
}</pre>Click to reveal answer
Which keyword marks a method in the base class to allow overriding?
✗ Incorrect
The
virtual keyword marks a method as overridable in the base class.What keyword do you use in the derived class to replace a base class virtual method?
✗ Incorrect
The
override keyword replaces the base class virtual method in the derived class.If a base class method is not virtual, what happens if you try to override it?
✗ Incorrect
You get a compiler error because only virtual or abstract methods can be overridden.
Calling a virtual method on a base class reference that points to a derived object calls:
✗ Incorrect
The derived class overridden method is called due to polymorphism.
Which keyword prevents further overriding of a virtual method?
✗ Incorrect
The
sealed keyword stops further overriding of a virtual method.Explain how method overriding works using
virtual and override keywords in C#.Think about how a base class method can be changed in a child class.
You got /4 concepts.
Describe what happens if you call a virtual method on a base class reference that points to a derived class object.
Focus on which method actually runs at runtime.
You got /4 concepts.