Inheritance in C# oops complete guide

by | Sep 29, 2023 | C# OOP | 0 comments

Inheritance

Table of content:

Topics
1Why i wrote this article
2Inheritance – complete guide
3All possible scenarios based/ tricky in/out type of Interview questions

Why i wrote this article?

When I was preparing c#/oops, the main challenge was information was scattered on Internet. Accumulating information like basic concepts, rules, all possible combination of interview questions, was a task. At time of interview, revising those concepts are very time consuming, each time we have to do the same activity.

This article is a detailed guid on “Inheritance in c#” topic that can help you understand the concept in detail, also will help you to prepare interview, so you do not need to check many articles on same topic!

Inheritance is one of the fundamental concepts in object-oriented programming (OOP). It allows you to create a new class (the derived class or subclass) based on an existing class (the base class or parent class). The derived class inherits properties (fields) and behaviors (methods) from the base class, and it can also add its own unique properties and behaviors.

Let’s explain basic inheritance concepts using C# as an example:

Base Class (Parent Class):

In this example, we have a base class called Animal. It has a property Name and a method Eat().

Derived Class (Subclass):

Here, we have a derived class called Dog, which inherits from the Animal base class. The Dog class has an additional method Bark().

Using Inheritance:

In this code:

  • We create an instance of the Dog class named myDog.
  • We set the Name property of myDog.
  • We can call the Eat() method on myDog, even though it’s not defined in the Dog class. This is because Dog inherits from Animal, and it inherits the Eat() method.
  • We can also call the Bark() method, which is specific to the Dog class.

Key points to understand about inheritance:

  1. Inheritance Relationship: The Dog class is a derived class of the Animal class. This means that a Dog is a specialized form of an Animal.
  2. Inherited Members: The Dog class inherits the Name property and Eat() method from the Animal class. This is a way to reuse code and create a hierarchy of classes.
  3. Adding Unique Behavior: The Dog class can have its own members (properties and methods), such as the Bark() method, which is specific to dogs.

Inheritance allows you to create a hierarchy of classes, where more specialized classes (derived classes) inherit and extend the functionality of more general classes (base classes). This promotes code reuse and helps you model real-world relationships and objects in your programs.

Multiple Inheritance with Interfaces:

Multiple inheritance in C# is a way to inherit or use features from multiple “parent” classes in one “child” class. However, C# doesn’t support multiple inheritance with classes directly due to potential confusion. Instead, it uses interfaces to achieve similar results.

Here’s a simple explanation with an example:

Multiple Inheritance with Interfaces:

Imagine you have different classes representing vehicles: Car, Boat, and Plane. Each has its own special abilities.

You want to create a class AmphibiousVehicle that can act like both a Car and a Boat. This is where multiple inheritance with interfaces comes into play:

Here’s what’s happening:

  • We create two interfaces, ICar and IBoat, defining what it means to be a car and a boat.
  • The AmphibiousVehicle class implements both interfaces, so it can perform actions like both a car and a boat.
  • In the Main method, we create an AmphibiousVehicle object and use it to drive and sail.

This way, C# allows you to inherit abilities from multiple “parent” interfaces to build versatile classes like AmphibiousVehicle.

New vs Override

New– reference type specific

Override– Object type specific(actual object)

Example-

  1. Animal myDog = new Dog();

In order to understand concept and examples in this article, lets understand

  • new Dog() here is actual object
  • Animal myDog = here is what actual object of Dog is referencing.

New

The new Keyword for Method Hiding

The new keyword is used when you want to hide a method from the base class and provide a different implementation in the derived class. It is reference type-specific, which means that the behaviour depends on the declared type of the reference, not the actual type of the object.

Consider the following example:

What will be the output?

Answer: // Calls Animal's MakeSound, not Dog’s because we are using new which is referencing type specefic, here myDog is Animal (referencing type not actual object)

Override

The override Keyword for Method Overriding

The override keyword is used when you want to provide a specific implementation of a method in a derived class that overrides the base class’s method. It is object type-specific, which means that the behavior depends on the actual type of the object.

Consider the following example:

What is output?

// Calls Dog's MakeSound

Lets understand what was happened in above examples-

Override

So here, its important to understand that in this case we used “Override” in child method, and we are assigning child object to parents object. So, child method was overridden already with child’s dogs bark! and we assigned this to parents declared reference type “Animal myDog”

New

And, when we used New in that case, child class method provided new definition of its own, and hided the relation of its parent (cut off)

In this case, even we are assigning childs Dogs bark, child got its own. so “Animal myDog” will use parents method only as child method did not override parents method.

This concept is very important and by using this memo, we can now remember this important aspect of inheritance concept, it will help you solving numerous interview input/output based questions based on inheritance like cut-off relation, multi level etc., we are going to discuss further in this article-

Examples asked in different interviews-

1 What if child class has no method?

Here’s an example where a child class has no methods or fields of its own and is essentially empty. The child class inherits all its behaviour from the base class:

Output- Calls Animal’s MakeSound method

2 What if we do not define override or new?

Answer- it will give compile warning “use override or new” , but wont give error.

By default it will use “New” behavior’s not override

Other Examples-

without using override and New with virtual? = it will behave like New by default

Same output , if we use “New” in this case

As earlier discussed, if using Override, then child call will replace its own method.(cats)

3 All examples above used Virtual in parent, what if we do not use them?

4 Using New without virtual?

output-

5 What if not using “New” in this case?

Output=-

Still the same result

Awesome! you learned the basic. Now its time to show off!

We will now learn and practice more tricky code, that often being asked in interviews.

After practicing these, i bet, you do not have to go to any other blog to learn the remaining! concepts, or more input/output type of practice question sets

Understanding Method Inheritance and Overriding in a Three-Level (multi-level) Hierarchy

Type 1 Cut-off relation in multi level inheritance while using override, and new with virtual.

in order to understand simply, we will use grandfather, father, and child terms, so our brain is focusing on the concept not consuming neurons in terminologies!

Certainly, let’s illustrate the concept of a “cut-off relation” using a simpler example with three levels of inheritance involving a grandfather, father, and child:

Now using method in child (third level) with new keyword

// still same result

// Calls Father's overridden Display method

What if we use override in Childs method?

1 Example- marked as override cannot be marked as new or virtual

// Output

Example 2

Example 3

Cut off relation-

Grand Father and Child, middle (father used new to cut off) in this case referencing type will always use grand father method

Example- Question based on base class and child class constructor accessibility level

Example – Using This and Base keyword

Congratulations, you are now expert in this topic, but please do not forget to revise and do handson practical in any code editor!

0 Comments

Related Posts

Delegates in C#: Complete tutorial

Learn Delegates c# In C#, a delegate is a type that represents references to methods with a particular parameter list and return type. Delegates provide a way to encapsulate a method, and they are often used for defining callback methods and implementing event...

Index:C# OOP

Delegates in C#: Complete tutorial

Learn Delegates c# In C#, a delegate is a type that represents references to methods with a particular parameter list and return type. Delegates provide a way to encapsulate a method, and they are often used for defining callback methods and implementing event...

Learn C# oops Polymorphism

Polymorphism Simplifying Polymorphism in C# with Examples Polymorphism is a fundamental concept in object-oriented programming (OOP), and it can be understood more easily by breaking it down into its key components. What is Polymorphism? At its core, polymorphism...