What is the output of this C# program?
using System; class Animal { public virtual void Speak() { Console.WriteLine("Animal speaks"); } } class Dog : Animal { public override void Speak() { Console.WriteLine("Dog barks"); } } class Program { static void Main() { Animal a = new Dog(); a.Speak(); } }
Remember that virtual methods allow derived classes to provide their own implementation.
The variable a is of type Animal but refers to a Dog object. Because Speak is virtual and overridden in Dog, the Dog version runs, printing "Dog barks".
What will this program print?
using System; class Base { public void Show() { Console.WriteLine("Base Show"); } } class Derived : Base { public new void Show() { Console.WriteLine("Derived Show"); } } class Program { static void Main() { Base b = new Derived(); b.Show(); } }
Check if the base method is virtual or not.
The base method Show is not virtual, so the call b.Show() uses the base class method even though b refers to a Derived object.
What is the output of this program?
using System; class A { public virtual void Print() { Console.WriteLine("A"); } } class B : A { public override void Print() { Console.WriteLine("B"); base.Print(); } } class C : B { public override void Print() { Console.WriteLine("C"); base.Print(); } } class Program { static void Main() { A obj = new C(); obj.Print(); } }
Follow the calls from the most derived class up to base classes.
The call obj.Print() runs C.Print() which prints "C" then calls B.Print(). B.Print() prints "B" then calls A.Print() which prints "A". So the output is:
C
B
A
What error does this code produce?
using System; class Parent { public virtual void Display() { Console.WriteLine("Parent Display"); } } class Child : Parent { public void Display() { Console.WriteLine("Child Display"); } } class Program { static void Main() { Parent p = new Child(); p.Display(); } }
Check if the child method overrides or hides the base method.
The Child.Display method does not use override keyword, so it hides the base method instead of overriding it. The call p.Display() uses the base class method, printing "Parent Display".
Which statement best explains why C# uses virtual and override keywords for method overriding?
Think about safety and clarity in overriding methods.
The virtual keyword marks a method as overridable. The override keyword tells the compiler that the method is intended to override a base virtual method. This helps catch mistakes like misspelling or wrong signatures.