
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Arithmetic Operators
- C# - Assignment Operators
- C# - Relational Operators
- C# - Logical Operators
- C# - Bitwise Operators
- C# - Miscellaneous Operators
- C# - Operators Precedence
- C# Conditional Statements
- C# - Decision Making
- C# - If
- C# - If Else
- C# - Nested If
- C# - Switch
- C# - Nested Switch
- C# Control Statements
- C# - Loops
- C# - For Loop
- C# - While Loop
- C# - Do While Loop
- C# - Nested Loops
- C# - Break
- C# - Continue
- C# OOP & Data Handling
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
C# - Inheritance
One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on.
Base and Derived Classes
A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.
Syntax
Following is the syntax used in C# for creating derived classes −
<acess-specifier> class <base_class> { ... } class <derived_class> : <base_class> { ... }
Example of Inheritance
In this example, we create an inheritance by considering a base class 'Shape' and its derived class 'Rectangle' −
using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // Derived class class Rectangle: Shape { public int getArea() { return (width * height); } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. Console.WriteLine("Total area: {0}", Rect.getArea()); Console.ReadKey(); } } }
When the above code is compiled and executed, it produces the following result −
Total area: 35
Initializing Base Class
When the derived class inherits from a base class, we can initialize the base class using the base
keyword in the constructor of the derived class.
The derived class inherits the base class member variables and member methods. Thus, the base class object must be created before the derived class object. We can specify the base class initialization in the member initialization list.
Syntax
Let's see the initialization syntax of the base class −
class BaseClass { public BaseClass(int value) { Console.WriteLine("Base class constructor called with value: " + value); } } class DerivedClass : BaseClass { public DerivedClass(int value) : base(value) { Console.WriteLine("Derived class constructor called."); } }
Example
The following program demonstrates. How we can initialize the base class member variable in the derived class −
using System; namespace RectangleApplication { class Rectangle { //member variables protected double length; protected double width; public Rectangle(double l, double w) { length = l; width = w; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } } class Tabletop : Rectangle { private double cost; // initializing base class member variable public Tabletop(double l, double w) : base(l, w) { } public double GetCost() { double cost; cost = GetArea() * 70; return cost; } public void Display() { base.Display(); Console.WriteLine("Cost: {0}", GetCost()); } } class ExecuteRectangle { static void Main(string[] args) { Tabletop t = new Tabletop(4.5, 7.5); t.Display(); Console.ReadLine(); } } }
When the above code is compiled and executed, it produces the following result −
Length: 4.5 Width: 7.5 Area: 33.75 Cost: 2362.5
Single Inheritance
Single inheritance is a basic type of inheritance where a class inherits from another single class.
Example
The following example demonstrates single inheritance:
using System; class Parent { public void Display() { Console.WriteLine("This is the parent class."); } } class Child : Parent { public void Show() { Console.WriteLine("This is the child class."); } } class Program { static void Main() { Child obj = new Child(); obj.Display(); // Inherited from Parent obj.Show(); // Defined in Child } }
When executed, this program outputs:
This is the parent class. This is the child class.
Multi-Level Inheritance
Multi-level inheritance is implements when a class inherits from another derived class, which creates a chain of inheritance.
Example
The following example demonstrates multi-level inheritance:
using System; class Grandparent { public void Display() { Console.WriteLine("Grandparent class."); } } class Parent : Grandparent { } class Child : Parent { } class Program { static void Main() { Child obj = new Child(); obj.Display(); // Inherited from Grandparent } }
When executed, this program outputs:
Grandparent class.
Hierarchical Inheritance
Hierarchical inheritance occurs when multiple classes inherit from a single base class.
Example
The following example demonstrates hierarchical inheritance:
using System; class Vehicle { public void Start() { Console.WriteLine("Vehicle is starting."); } } class Car : Vehicle { public void Drive() { Console.WriteLine("Car is driving."); } } class Bike : Vehicle { public void Ride() { Console.WriteLine("Bike is riding."); } } class Program { static void Main() { Car myCar = new Car(); myCar.Start(); // Inherited method myCar.Drive(); Bike myBike = new Bike(); myBike.Start(); // Inherited method myBike.Ride(); } }
When executed, this program outputs:
Vehicle is starting. Car is driving. Vehicle is starting. Bike is riding.
Method Overriding in Inheritance
In inheritance, method overriding allows you to rewrite a method from the base class in a derived class using the override keyword
Example
The following example demonstrates method overriding in inheritance:
using System; class Animal { public virtual void MakeSound() { Console.WriteLine("Animal makes a sound."); } } class Dog : Animal { public override void MakeSound() { Console.WriteLine("Dog barks."); } } class Program { static void Main() { Animal myPet = new Dog(); myPet.MakeSound(); // Calls overridden method } }
When executed, this program outputs:
Dog barks.
Using 'base' Keyword in Inheritance
The "base" keyword in inheritance allows a derived class to access the members of its base class.
Example
The following example demonstrates the use of the base
keyword to call a base class constructor from a derived class:
using System; class Person { public string Name; public Person(string name) { Name = name; } } class Student : Person { public int RollNo; public Student(string name, int rollNo) : base(name) { RollNo = rollNo; } public void Display() { Console.WriteLine($"Name: {Name}, Roll No: {RollNo}"); } } class Program { static void Main() { Student student = new Student("Sudhir", 101); student.Display(); } }
When executed, this program outputs:
Name: Sudhir, Roll No: 101
Preventing Inheritance with sealed Keyword
You can prevent a class from inheritance by using the "sealed" keyword. The "sealed" keyword is used before the class keyword during class declaration, and no other class can derive from it.
Example
The following example demonstrates how a sealed class prevents further inheritance:
sealed class FinalClass { public void Display() { Console.WriteLine("This is a sealed class."); } } // ERROR: class DerivedClass : FinalClass {} // Cannot inherit
Multiple Inheritance
Multiple inheritance states the ability of a class to inherit from multiple base classes. But C# does not support multiple inheritance. However, we can implement multiple inheritance using the interfaces in c#.
Where an interface is a collection of the abstract method that a class implements to provide specific behaviour.
Example
In the following example, we construct multiple inheritance using interfaces in C# −
using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // Base class PaintCost public interface PaintCost { int getCost(int area); } // Derived class class Rectangle : Shape, PaintCost { public int getArea() { return (width * height); } public int getCost(int area) { return area * 70; } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // Print the area of the object. Console.WriteLine("Total area: {0}", Rect.getArea()); Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area)); Console.ReadKey(); } } }
When the above code is compiled and executed, it produces the following result −
Total area: 35 Total paint cost: $2450