Home C# Inheritance in C# tutorial

Inheritance in C# tutorial

Inheritance is a key feature of object-oriented programming in C#.

It allows a class to inherit fields, methods, and properties from another class, promoting code reusability and simplifying the structure.

Inheritance is especially useful for creating a hierarchy of related classes and for polymorphism.

This tutorial will cover:

1. Basics of Inheritance

In C#, inheritance is implemented using a colon (:) after the derived (child) class name, followed by the base (parent) class name. The derived class inherits all accessible members (fields, properties, and methods) of the base class.

Syntax:

public class BaseClass
{
    // Base class members
}

public class DerivedClass : BaseClass
{
    // Additional members specific to DerivedClass
}

Example:

using System;

public class Animal
{
    public string Name;

    public void Eat()
    {
        Console.WriteLine(Name + " is eating.");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine(Name + " is barking.");
    }
}

public class InheritanceExample
{
    public static void Main()
    {
        Dog myDog = new Dog();
        myDog.Name = "Buddy";
        myDog.Eat();  // Inherited from Animal
        myDog.Bark(); // Specific to Dog
    }
}

In this example:

  • The Dog class inherits the Name property and Eat method from the Animal class.
  • Dog also has its own method, Bark, which is unique to the Dog class.

Output:

Buddy is eating.
Buddy is barking.

2. Using base to Access the Parent Class

The base keyword is used in the derived class to access members of the base class. It’s commonly used to call base class constructors and methods when overriding.

Example: Using base to Call Base Class Constructor

using System;

public class Animal
{
    public string Name;

    public Animal(string name)
    {
        Name = name;
    }

    public void Eat()
    {
        Console.WriteLine(Name + " is eating.");
    }
}

public class Dog : Animal
{
    public Dog(string name) : base(name) // Calls the base class constructor
    {
    }

    public void Bark()
    {
        Console.WriteLine(Name + " is barking.");
    }
}

public class BaseExample
{
    public static void Main()
    {
        Dog myDog = new Dog("Buddy");
        myDog.Eat();
        myDog.Bark();
    }
}

In this example:

  • Dog inherits the Name property from Animal.
  • The Dog constructor uses base(name) to call the Animal constructor, passing in the name.

Output:

Buddy is eating.
Buddy is barking.

3. Overriding Methods

In C#, you can use the virtual keyword to make a method in the base class available for overriding in the derived class. The derived class then uses the override keyword to modify the behavior of the base class method.

Example: Overriding a Method

using System;

public class Animal
{
    public string Name;

    public Animal(string name)
    {
        Name = name;
    }

    public virtual void MakeSound()
    {
        Console.WriteLine(Name + " makes a sound.");
    }
}

public class Dog : Animal
{
    public Dog(string name) : base(name)
    {
    }

    public override void MakeSound()
    {
        Console.WriteLine(Name + " barks.");
    }
}

public class OverrideExample
{
    public static void Main()
    {
        Animal myAnimal = new Animal("Generic Animal");
        myAnimal.MakeSound();

        Dog myDog = new Dog("Buddy");
        myDog.MakeSound();
    }
}

In this example:

  • MakeSound is defined as virtual in Animal, allowing it to be overridden in Dog.
  • The Dog class provides a specific implementation for MakeSound by using override.

Output:

Generic Animal makes a sound.
Buddy barks.

4. Sealed Classes and Methods

The sealed keyword prevents further inheritance. You can use it on a class to prevent it from being inherited or on a method to prevent it from being overridden in derived classes.

Example: Sealing a Class and a Method

using System;

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Animal makes a sound.");
    }
}

public class Dog : Animal
{
    public sealed override void MakeSound() // Sealed method
    {
        Console.WriteLine("Dog barks.");
    }
}

// This would cause an error because Dog is sealed
// public class SmallDog : Dog
// {
// }

public class SealedExample
{
    public static void Main()
    {
        Dog myDog = new Dog();
        myDog.MakeSound();
    }
}

In this example:

  • The MakeSound method in Dog is marked as sealed, so it cannot be overridden by any further derived classes.
  • Attempting to inherit from Dog or override MakeSound in a subclass of Dog will cause a compile-time error.

Output:

Dog barks.

5. Practical Examples of Inheritance

Example 1: Shape Hierarchy

Inheritance is useful for creating a hierarchy of related classes, such as different shapes in a graphics program.

using System;

public class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine("Drawing a shape.");
    }
}

public class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a circle.");
    }
}

public class Rectangle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a rectangle.");
    }
}

public class ShapeExample
{
    public static void Main()
    {
        Shape myShape = new Shape();
        myShape.Draw();

        Shape myCircle = new Circle();
        myCircle.Draw();

        Shape myRectangle = new Rectangle();
        myRectangle.Draw();
    }
}

Explanation:

  • The Shape class has a Draw method, which is overridden in Circle and Rectangle.
  • Using polymorphism, we can create instances of Shape that refer to Circle and Rectangle, calling the appropriate Draw method.

Output:

Drawing a shape.
Drawing a circle.
Drawing a rectangle.

Example 2: Vehicle Hierarchy

Another example of inheritance is creating a hierarchy for different types of vehicles.

using System;

public class Vehicle
{
    public int Speed { get; set; }

    public virtual void Start()
    {
        Console.WriteLine("Vehicle starts moving.");
    }
}

public class Car : Vehicle
{
    public int NumberOfDoors { get; set; }

    public override void Start()
    {
        Console.WriteLine("Car starts driving.");
    }
}

public class Bike : Vehicle
{
    public bool HasPedals { get; set; }

    public override void Start()
    {
        Console.WriteLine("Bike starts riding.");
    }
}

public class VehicleExample
{
    public static void Main()
    {
        Vehicle myVehicle = new Vehicle();
        myVehicle.Start();

        Car myCar = new Car { NumberOfDoors = 4 };
        myCar.Start();

        Bike myBike = new Bike { HasPedals = true };
        myBike.Start();
    }
}

Explanation:

  • The Vehicle class has a Start method that is overridden in both Car and Bike.
  • The derived classes Car and Bike have specific properties (NumberOfDoors for Car and HasPedals for Bike) and behaviors for Start.

Output:

Vehicle starts moving.
Car starts driving.
Bike starts riding.

Example 3: Employee Hierarchy

Inheritance is often used to model entities with shared attributes and behaviors in business applications.

using System;

public class Employee
{
    public string Name { get; set; }

    public virtual void Work()
    {
        Console.WriteLine(Name + " is working.");
    }
}

public class Manager : Employee
{
    public override void Work()
    {
        Console.WriteLine(Name + " is managing the team.");
    }
}

public class Developer : Employee
{
    public override void Work()
    {
        Console.WriteLine(Name + " is writing code.");
    }
}

public class EmployeeExample
{
    public static void Main()
    {
        Employee manager = new Manager { Name = "Alice" };
        Employee developer = new Developer { Name = "Bob" };

        manager.Work();
        developer.Work();
    }
}

Explanation:

  • Employee has a Work method, which is overridden by both Manager and Developer.
  • Manager and Developer represent specific types of employees with unique job descriptions.

Output:

Alice is managing the team.
Bob is writing code.

Summary

Inheritance in C# is a powerful way to create a hierarchy of related classes.

Here’s a recap of the key concepts:

    • Basic Inheritance: Allows a derived class to inherit members from a base class.
    • base Keyword: Used to access members of the base class, including calling constructors.
  • Overriding Methods: Use virtual in the base class and override in the derived class to change behavior.
  • Sealed Classes and Methods: Use sealed to prevent further inheritance or overriding.
  • Practical Examples: Inheritance can be used to model real-world hierarchies, such as shapes, vehicles, and employees.

Inheritance is an essential part of object-oriented programming, helping you organize and reuse code effectively while promoting flexibility through polymorphism.

You may also like