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

Method overriding with virtual and override in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Avirtual
Boverride
Cnew
Dabstract
What keyword do you use in the derived class to replace a base class virtual method?
Avirtual
Bnew
Coverride
Dsealed
If a base class method is not virtual, what happens if you try to override it?
ACompiler error
BIt overrides successfully
CRuns base method anyway
DMethod is hidden but not overridden
Calling a virtual method on a base class reference that points to a derived object calls:
ABase class method
BDerived class overridden method
CCompiler error
DRandom method
Which keyword prevents further overriding of a virtual method?
Avirtual
Boverride
Cabstract
Dsealed
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.