Skip to main content

How to Implement Inheritance in Csharp

Understanding inheritance is a key part of mastering object-oriented programming in C#. If you're looking to simplify and reuse code, inheritance is a feature you shouldn't overlook. Let's dive right into how you can implement it in your C# applications.

What Is Inheritance in C#?

Inheritance lets you create a new class based on an existing one. The new class, called the "derived class," inherits methods, properties, and fields from the "base class." It’s like children inheriting characteristics from their parents.

But why is this useful? It saves time, reduces redundancy, and keeps code organized. For example, imagine you’re building a software program for a store. Instead of creating the same features for customers, employees, and administrators repeatedly, you can add shared attributes to a single parent class.

To learn more about the core concepts of inheritance, check out this friendly guide to C# inheritance.


How to Use Inheritance in C#

Before diving into examples, let’s grasp the basics.

  • The base class is the one that provides usable properties and methods.
  • The derived class extends the base class and, optionally, adds its own features.

Syntax:

class BaseClass  
{  
    public string Name = "Parent Class";  

    public void ShowMessage()  
    {  
        Console.WriteLine("This is a message from the base class.");  
    }  
}  

class DerivedClass : BaseClass  
{  
    public void PrintDerivedMessage()  
    {  
        Console.WriteLine("This is a message from the derived class.");  
    }  
}  

You can see the DerivedClass is inheriting all public members of BaseClass. The : symbol is used to signify inheritance.


Code Examples

Let’s explore more hands-on examples to bring clarity.

Example 1: Basic Inheritance

class Animal  
{  
    public void Eat()  
    {  
        Console.WriteLine("The animal is eating.");  
    }  
}  

class Dog : Animal  
{  
    public void Bark()  
    {  
        Console.WriteLine("The dog barks.");  
    }  
}  

class Program  
{  
    static void Main(string[] args)  
    {  
        Dog dog = new Dog();  
        dog.Eat(); // Accessing method from Animal  
        dog.Bark(); // Accessing method from Dog  
    }  
}

Explanation:

  1. Animal serves as the base class with an Eat() method.
  2. Dog inherits the Animal class and gains access to its behavior.
  3. You can call the Eat() method even though the object dog belongs to the Dog class.

Example 2: Adding Custom Features

class Car  
{  
    public string Brand = "Generic Brand";  

    public void Start()  
    {  
        Console.WriteLine("Car is starting.");  
    }  
}  

class Tesla : Car  
{  
    public void AutoPilot()  
    {  
        Console.WriteLine("Tesla is on autopilot mode.");  
    }  
}  

class Program  
{  
    static void Main()  
    {  
        Tesla myTesla = new Tesla();  
        Console.WriteLine(myTesla.Brand); // Inherited from Car  
        myTesla.Start(); // Method from Car  
        myTesla.AutoPilot(); // Method exclusive to Tesla  
    }  
}

Example 3: Using base Keyword

class Parent  
{  
    public string FamilyName = "Smith";  

    public Parent(string name)  
    {  
        Console.WriteLine($"Hello, I am {name} from the {FamilyName} family.");  
    }  
}  

class Child : Parent  
{  
    public Child(string name) : base(name)  
    {  
        Console.WriteLine("I am a child of the parent class.");  
    }  
}  

class Program  
{  
    static void Main()  
    {  
        Child child = new Child("John");  
    }  
}

Explanation:

  • The base keyword calls the parent class constructor from the derived class.

Example 4: Overriding Methods

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

class Cat : Animal  
{  
    public override void Speak()  
    {  
        Console.WriteLine("The cat meows.");  
    }  
}  

class Program  
{  
    static void Main()  
    {  
        Animal myAnimal = new Cat();  
        myAnimal.Speak(); // Outputs: The cat meows  
    }  
}

Key Points:

  • The virtual keyword enables method overriding.
  • The override keyword modifies the inherited behavior in the derived class.

Example 5: Sealing Methods

class Parent  
{  
    public virtual void Show()  
    {  
        Console.WriteLine("This is the parent class.");  
    }  
}  

class Child : Parent  
{  
    public sealed override void Show()  
    {  
        Console.WriteLine("This is the child class.");  
    }  
}  

class GrandChild : Child  
{  
    // Cannot override Show() because it is sealed in Child  
}

Conclusion

Inheritance in C# is simple but incredibly powerful. It helps you write cleaner, reusable code while avoiding unnecessary duplications. Whether it’s sharing basic operations between classes or creating unique yet linked features, inheritance can do that.

Ready to take the next step? You might find related resources like C# OOP: A Deep Dive into Object-Oriented Programming helpful to strengthen your foundation on object-oriented principles. Feel free to experiment with the examples above and implement them in your next project.

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

Linux Network Troubleshooting

If you've spent any time as a sysadmin — or honestly, just as someone who's had to fix their own home network at 11pm — you know that connectivity issues are one of the most common headaches out there. The good news is that a handful of core tools and a methodical approach can take you from "why isn't this working" to a root cause pretty quickly.  This guide walks through the essentials: configuring interfaces, managing routes, and diagnosing problems when things go sideways. Configuring Network Interfaces Your network interfaces are the actual bridge between your machine and the outside world, so getting them configured correctly is step one for any kind of reliable connectivity. Doing It Manually ifconfig is the old-school, tried-and-true tool for this on Unix-like systems. To see everything currently configured, run: ifconfig -a If you need to manually set up a specific interface — assigning an IP, a netmask, and bringing it online — it looks like this: ifconf...