Inheritance in C#: Extending Classes


Inheritance is a key concept in C# and object-oriented programming. This guide explores how you can extend classes, reuse code, and create hierarchies using inheritance in C#.


What is Inheritance?


Inheritance is a mechanism that allows a new class (derived or subclass) to inherit the properties and behaviors of an existing class (base or superclass). It promotes code reusability and establishes an "is-a" relationship between classes.


Base and Derived Classes


The base class (or superclass) is the class being extended, and the derived class (or subclass) is the one doing the extending. The derived class inherits the attributes and methods of the base class and can also add new attributes and methods.


Example of a base class and a derived class:


public class Vehicle
{
public string Make;
public string Model;
public void Start()
{
Console.WriteLine("Vehicle is starting.");
}
}
public class Car : Vehicle
{
public void Accelerate()
{
Console.WriteLine("Car is accelerating.");
}
}
Car myCar = new Car();
myCar.Make = "Honda";
myCar.Model = "Civic";
myCar.Start();
myCar.Accelerate();

Accessing Base Class Members


In a derived class, you can access the attributes and methods of the base class using the `base` keyword. This is useful when you want to call or override base class members.


Example of accessing base class members:


public class Car : Vehicle
{
public void Accelerate()
{
Console.WriteLine("Car is accelerating.");
}
public void StartCar()
{
base.Start(); // Calling the base class's Start method
}
}
Car myCar = new Car();
myCar.StartCar(); // Calls the base class's Start method

Method Overriding


Inheritance allows you to override base class methods in the derived class. This means the derived class can provide its own implementation of a method with the same signature as the base class.


Example of method overriding:


public class Vehicle
{
public void Start()
{
Console.WriteLine("Vehicle is starting.");
}
}
public class Car : Vehicle
{
public new void Start()
{
Console.WriteLine("Car is starting.");
}
}
Car myCar = new Car();
myCar.Start(); // Calls the Car class's Start method

Conclusion


Inheritance in C# is a powerful concept for extending classes and building class hierarchies. You've learned about base and derived classes, accessing base class members, and method overriding. Inheritance promotes code reuse and enhances the organization and structure of your programs.


Practice using inheritance in your C# programs to create complex class hierarchies and enhance code reusability. As you continue your programming journey, you'll explore more advanced inheritance concepts and design patterns to take your coding skills to the next level.