C# interview questions and answers on inheritance

What are the 4 pillars of any object oriented programming language?
2. Inheritance
3. Encapsulation
4. Polymorphism

Do structs support inheritance?
No, structs do not support inheritance, but they can implement interfaces.

What is the main advantage of using inheritance?
Code reuse

Is the following code legal?
class ChildClass : ParentClassA, ParentClassB

No, a child class can have only one base class. You cannot specify 2 base classes at the same time. C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance.

What will be the output of the following code?
using System;
public class BaseClass
public BaseClass()
Console.WriteLine("I am a base class");
public class ChildClass : BaseClass
public ChildClass()
Console.WriteLine("I am a child class");
static void Main()
ChildClass CC = new ChildClass();
I am a base class
I am a child class
This is because base classes are automatically instantiated before derived classes. Notice the output, The BaseClass constructor executed before the ChildClass constructor.

Does C# support multiple class inheritance?
No, C# supports single class inheritance only. However classes can implement multiple interfaces at the same time.

No comments:

Top Blogs