Skip to main content

Using Inheritance with C# Code Examples

 

Ziggy Rafiq Blog Post on Using Inheritance with C# Code Examples

Overview

In this article, we will explore the concept of Inheritance, which is a fundamental concept of Object-Oriented Programming (OOP) and is applicable to several programming languages including Java, C++, Python, and TypeScript. We will delve into the what, why, and how of using Inheritance and discuss the best practices for using Inheritance in C#. Additionally, we will provide code examples specifically tailored to C#.

What is Inheritance

Inheritance is one of the fundamental concepts of object-oriented programming (OOP) in C#. It allows a class to inherit properties and behaviour from another class, called the base class or parent class. The class that inherits from the base class is called the derived class or child class.

In C#, inheritance is achieved through the use of the: symbol followed by the name of the base class. Here's an example of how to declare a derived class that inherits from a base class:

In this example, the Animal class is the base class, and the Dog class is the derived class that inherits from it. The Dog class has access to the Eat and Sleep methods of the Animal class, as well as its own Bark method.


Using Inheritance with C# Code Example Code Example of Animal


Why use Inheritance

Using inheritance provides several benefits as Inheritance is used in C# for five core reasons which are as following below.

  • Code Reuse: Inheritance allows you to reuse code from an existing class instead of rewriting it in a new class. This saves time and reduces the chances of introducing bugs.
  • Polymorphism: Inheritance enables polymorphism, which means that objects of the derived class can be treated as objects of the base class. This allows for more flexibility in programming and simplifies code maintenance.
  • Abstraction: Inheritance enables the creation of abstract classes and interfaces, which define a common set of properties and behaviours for a group of related classes. This promotes code modularity and simplifies program design.

In a nutshell, using inheritance is a powerful feature of C# that allows for code reuse, polymorphism, and abstraction. It is an essential tool for creating complex software systems that are easy to maintain and extend.


How to use Inheritance

To use inheritance in C#, you can create a new class that inherits the properties and methods of an existing class (base class). The new class is called the derived class, and it can add new properties and methods or override the properties and methods of the base class.

In the example below, the Animal class is the base class, and the Dog class is the derived class that inherits from it. The Dog class has access to the Eat and Sleep methods of the Animal class, as well as its own Bark method.

Using Inheritance with C# Code Example Code Example of Animal Dog


To use the Dog class in your program, you can create an instance of it like this:

Using Inheritance with C# Code Example Code Example of Animal Dog in Program Console App

This will create a new instance of the Dog class and call its Bark method, as well as the Eat and Sleep methods inherited from the Animal class.

You can also override the properties and methods of the base class in the derived class like this:

Using Inheritance with C# Code Example Code Example of Animal Dog in Program Console App Override Example

In this example, the Animal class has a MakeSound method that is marked as virtual, which means it can be overridden in derived classes. The Dog class overrides the MakeSound method and provides its own implementation. When you call the MakeSound method on a Dog instance, it will output "Barking..." instead of "Animal sound...".

 Using inheritance is a powerful tool in C# that allows you to reuse code, promote code modularity and organization, and enable polymorphism and extensibility in your programs.

Best Practice Using Inheritance 

There are common 7 best practices to follow when using inheritance in C#, which are as follows below.

  • Use inheritance only when it makes sense: Inheritance is a powerful tool, but it can also make your code more complex and harder to maintain. Use inheritance only when it makes sense for your program's design and requirements.
  •  Favour composition over inheritance: In some cases, it may be better to use composition (creating an object that contains other objects) instead of inheritance. This can make your code more modular and easier to test and maintain.
  •  Follow the Liskov substitution principle: The Liskov substitution principle states that a derived class should be able to be used in place of its base class without causing any unexpected behaviour. Make sure that your derived classes follow this principle to avoid bugs and unexpected behaviour.
  •  Use abstract classes and interfaces to define contracts: Abstract classes and interfaces define a set of properties and methods that a class must implement. Use them to define contracts that your derived classes must follow.
  •  Use the sealed keyword judiciously: The sealed keyword prevents a derived class from being further derived. Use it judiciously, as it can limit the extensibility of your program.
  •  Avoid deep class hierarchies: Deep class hierarchies can make your code harder to understand and maintain. Try to keep your class hierarchies shallow, with no more than 3 or 4 levels.
  •  Avoid duplication of code: Inheritance is a tool for code reuse, so make sure that you are actually reusing code when you use it. Avoid duplicating code in your derived classes, as this can lead to bugs and make your code harder to maintain.

Using inheritance in C# can make your code more modular, reusable, and extensible. However, it is important to use it judiciously and follow best practices to ensure that your code is maintainable and easy to understand.

Comments

Most Viewed Ziggy Rafiq Blog Posts

A Complete Guide to Using GUIDs in C# with Code Examples

  Overview In this post, we are looking at GUIDs (Globally Unique Identifiers), which are widely used in C# for generating unique identifiers for objects, entities, and resources in a system. In this post, we'll explore the basics of GUIDs in C#, their advantages, and how to convert strings to GUIDs. In this post, we have used Guid Generator to create the GUID from the following URL Address https://guidgenerator.com/ What is GUID GUID (Globally Unique Identifier) in C# is a 128-bit value that is used to identify objects, entities, or resources in a unique manner across different systems and applications. It is also known as UUID (Universally Unique Identifier) in some other programming languages.   GUIDs are generated using a combination of unique factors such as the MAC address of the network adapter, the current time and date, and a random number. The resulting GUID is a string of 32 hexadecimal digits separated by hyphens, such as "b86f2096-237a-4059-8329-1bbcea72769b...

Primitives Data Types and None-Primitives Data Types in C# with Code Examples

  Overview I wrote this post to provide an explanation of primitive and non-primitive data types in C#. C# is a strongly typed programming language, where each variable and expression must have a specific data type. C# data types are categorized into two primary groups: primitive data types and non-primitive data types. Primitive data types are the simplest data types available in programming languages. They are typically pre-defined data types and can represent a single value, such as a boolean value, character, or integer. Examples of primitive data types include int, char, float, double, and boolean, which are common in programming languages like C++, C, and Java. Non-primitive data types are also referred to as composite data types or reference data types. They are constructed from primitive data types and are more complex than primitive data types. Non-primitive data types can hold multiple values and allow for the creation of more intricate data structures like tables, li...

How to use Enum Data Values with .Net 6.0 Framework and Entity Framework Core 6

How to use Enum Data Values with .Net 6.0 Framework and Entity Framework Core 6 Overview An Enum (Enumeration) is a group of constants that are read-only value types. By default, the first value of the Enum variable is 0 i.e. Here we will create an Enum of Priorities type with read-only values of Highest, Normal and Low. We will set the read-only values using an integer assigning a number next to the value. By default, the integer value will start with 0. Here we will be assigning the integer value next to the Enum value such as in the below example and we will use a comma (,) to separate the item in the list of Enum(Enumeration).  We create Enum by using the Enum keyword and then using class, interface, and abstract. The reason we use an Enum is to ensure we improve our application performance and improve application readability, and maintainability, and reduces the complexity of the application hence why if you take a look at the example below of Status (NotStarted, Started, Comp...