Inheritance in C# Language
Inheritance is a fundamental concept in object-oriented programming, and C# i
s no exception. It is a mechanism that allows one class to inherit the properties and behaviors (i.e., fields, properties, methods, and events) of another class. This powerful feature in C# promotes code reuse and supports the creation of a hierarchical class structure. In this post, we will explore the concept of inheritance in C# with examples.The Basics of Inheritance
In C#, you can create a new class by deriving from an existing class. The new class, called the derived class or subclass, inherits the members of the base class or superclass. The inheritance relationship is established using the : symbol.
Here’s a simple example to illustrate inheritance:
class Animal
{
public void Eat()
{
Console.WriteLine("Animal is eating.");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Dog is barking.");
}
}
In this example, we have two classes, Animal and Dog. The Dog class inherits from the Animal class. This means that the Dog class can access the Eat method defined in the Animal class and also has its own method Bark.
Accessing Base Class Members
When inheriting from a base class, you can access its members using the base keyword. For example:
class Cat : Animal
{
public void Meow()
{
Console.WriteLine("Cat is meowing.");
base.Eat(); // Access the Eat method from the base class.
}
}
In the Cat class, we can call the Eat method from the base class using base.Eat().
Constructors in Inheritance
Constructors are not inherited by default, but you can explicitly call the base class constructor using the base keyword in the derived class constructor:
class Vehicle
{
public string Name { get; set; }
public Vehicle(string name)
{
Name = name;
}
}
class Car : Vehicle
{
public Car(string name, int wheels) : base(name)
{
Wheels = wheels;
}
public int Wheels { get; set; }
}
In the example above, the Car class calls the constructor of the base class Vehicle using base(name) and also initializes its own property Wheels.
Method Overriding
Inheritance in C# also allows you to override methods in the base class. This is useful when you want to provide a specific implementation in the derived class. To override a method, use the override keyword:
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape.");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}
In the Circle class, we override the Draw method from the base class Shape to provide a custom implementation.
Discover more from PiEmbSysTech - Embedded Systems & VLSI Lab
Subscribe to get the latest posts sent to your email.



