Which of the following best explains why inheritance is used in C# programming?
Think about how inheritance helps programmers avoid rewriting the same code multiple times.
Inheritance allows a new class to take properties and methods from an existing class. This means you can reuse code instead of writing it again, which saves time and makes programs easier to maintain.
What is the output of this C# code?
class Animal { public void Speak() { System.Console.WriteLine("Animal speaks"); } } class Dog : Animal { public void Bark() { System.Console.WriteLine("Dog barks"); } } class Program { static void Main() { Dog d = new Dog(); d.Speak(); d.Bark(); } }
Remember that Dog inherits methods from Animal and can use both Speak and Bark.
The Dog class inherits the Speak method from Animal, so calling d.Speak() prints "Animal speaks". Then d.Bark() prints "Dog barks".
Look at this C# code. Why does it cause a compile-time error?
class Vehicle { public void Move() { System.Console.WriteLine("Vehicle moves"); } } class Car : Vehicle { public void Move(int speed) { System.Console.WriteLine($"Car moves at {speed} km/h"); } } class Program { static void Main() { Car c = new Car(); c.Move(); } }
Think about method hiding and how method signatures affect which method is called.
In C#, when a derived class defines a method with the same name but different parameters, it hides the base class method. Calling c.Move() without parameters causes a compile error because the base method is hidden and no matching method exists in Car.
Which of the following code snippets correctly shows how to inherit class Base in class Derived in C#?
Remember the symbol used in C# to indicate inheritance.
In C#, the colon : is used to indicate inheritance. So class Derived : Base { } means Derived inherits from Base.
You have two classes, Car and Bike, both with methods to start and stop. How does using inheritance help if you want to add a new method Refuel to both?
Think about how inheritance lets you write shared code once and reuse it.
Inheritance lets you put common methods like start, stop, and refuel in a base class (e.g., Vehicle). Car and Bike inherit from Vehicle, so you add Refuel once in Vehicle and both classes get it automatically. This makes maintenance easier.