Inheritance in C# is a fundamental object-oriented programming concept that enables a class (known as a derived or child class) to inherit fields, methods, properties, and other members from another class (known as a base or parent class). This allows code reusability, enhances maintainability, and supports hierarchical classification.
The concept of Inheritance in C# provides several advantages:
Inheritance in C# supports the following types:
C# does not support multiple class inheritance directly to avoid ambiguity issues, but similar functionality can be achieved using interfaces.
The syntax to declare inheritance is:
class BaseClass { public void DisplayMessage() { Console.WriteLine("This is the base class method."); } } class DerivedClass : BaseClass { public void ShowDerived() { Console.WriteLine("This is the derived class method."); } }
Access modifiers determine the accessibility of class members in inheritance.
| Modifier | Accessible in Derived Class? | Description |
|---|---|---|
| public | Yes | Accessible anywhere |
| private | No | Accessible only within the same class |
| protected | Yes | Accessible within the base class and its derived classes |
| internal | Only within same assembly | Not across different assemblies |
The base keyword is used to:
class Parent { public Parent() { Console.WriteLine("Parent constructor"); } } class Child : Parent { public Child() : base() { Console.WriteLine("Child constructor"); } }
Derived classes can override base class methods using the override keyword. The base method must be marked with virtual.
class Animal { public virtual void Speak() { Console.WriteLine("Animal speaks"); } } class Dog : Animal { public override void Speak() { Console.WriteLine("Dog barks"); } }
Consider a simple real-world scenario of Vehicle as a base class and Car and Bike as derived classes.
class Vehicle { public string Brand = "Generic Brand"; public void StartEngine() { Console.WriteLine("Engine Started"); } } class Car : Vehicle { public string Model = "Sedan"; } class Bike : Vehicle { public string Type = "Sport"; }
Here, Car and Bike classes can use methods and properties from the Vehicle class.
When a derived class object is created, the base class constructor is automatically called before the derived class constructor executes.
Sealed prevents further inheritance or method overriding.
sealed class FinalClass { // Cannot be inherited } class Base { public virtual void Show() {} } class Derived : Base { public sealed override void Show() { // Cannot be overridden again } }
Inheritance in C# is a key pillar of object-oriented programming that enhances reusability and maintainability by enabling one class to acquire the properties and behaviors of another. Understanding its principles, types, and real-world usage is essential for effective C# programming.
Copyrights © 2024 letsupdateskills All rights reserved