What is inheritance in C#?

Experience Level: Junior
Tags: C#

Answer

C# is an object oriented language which means it supports inheritance. Inheritance is the ability of one object to inherit properties and behavior of another object.

Look at the example below. We created the class Machine that defines the basic behavior of the Machine. Each instance of the class Machine will have method TurnOn and TurnOff, which means you will be able to turn the machine on and off.

We have then created class Radio and inherited it from the class Machine. Thanks to inheritance, the Radio class will have all methods that the Machine class has plus one new method Mute() using which you can mute the radio when it's turned on.

We also created class Fridge that is also inherited from the class Machine. It will have both methods TurnOn and TurnOff that were inherited from the class Machine. And it has one new method Freeze that can make the Fridge freeze its contents.

As you can see, both classes Radio and Fridge are using the shared piece of functionality that was inherited from the class machine. Thanks to this both machines can be turned on and off but each of the machine also got some additional features that extended the feature set of the Machine class.

This has one important effect. If you need to change the behavior of the method TurnOn or TurnOff in the future, you don't need to change two classes but you change just the class Machine and the changed behavior will automatically appear in both classes Radio and Fridge.

Example
public class Program 
{
  public static void Main() 
  {
    var myRadio = new Radio();
	myRadio.TurnOn();
  }
}

public class Radio : Machine
{
  public void Mute() 
  {
  }
}

public class Fridge : Machine
{
  public void Freeze()
  {
  }
}


public class Machine
{
  public void TrunOn()
  {
    // Some code here
  }
  
  public void TurnOff()
  {
    // Some code here
  }  
}
Other C# job interview questions
C# for beginners
C# for beginners

Are you learning C#? Try our test we designed to help you progress faster.

Test yourself