C# Inheritance: Basics and Practical Examples

Let's delve into the basics of inheritance in C# in a simple and concise manner.

The Syntax of Inheritance in C#

In C#, inheritance is achieved using the symbol followed by the name of the parent class. Here's a basic syntax.

class ParentClass
{
    // Parent class members
}

class ChildClass : ParentClass
{
    // Child class members
}

Example. Animal Inheritance hierarchy

Let's consider a simple example to illustrate inheritance in C#. We'll create a hierarchy of animals.

using System;

class Animal
{
    public void Eat()
    {
        Console.WriteLine("The animal is eating.");
    }
}
class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Woof! Woof!");
    }
}
class Cat : Animal
{
    public void Meow()
    {
        Console.WriteLine("Meow!");
    }
}

In this example

  • The animal is the parent class with a method Eat.
  • Dog and Cat are child classes inherited from Animals.
  • Dog has an additional method Bark, while Cat has Meo.

Access Modifiers and Inheritance

In C#, members of a base class can have different access modifiers (public, protected, private, internal). When a member is protected, it's accessible within the containing class and any class derived from it.

class Animal
{
    protected string species;
    public void SetSpecies(string species)
    {
        this.species = species;
    }
}
class Dog : Animal
{
    public void DisplaySpecies()
    {
        Console.WriteLine($"This is a {species}.");
    }
}


Similar Articles