Inheritance is a crucial concept in object-oriented programming (OOP) that allows a class to inherit properties and methods from another class. In C#, it promotes code reuse and establishes a hierarchical relationship between classes.
To create a derived class in C#, use the following syntax:
class DerivedClass : BaseClass
{
// Derived class members
}
The colon (:) indicates that the derived class inherits from the base class.
C# does not support multiple inheritance for classes, but it can be achieved using interfaces.
Use the 'base' keyword to access members of the base class from within the derived class:
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Dog : Animal
{
public override void MakeSound()
{
base.MakeSound(); // Call the base class method
Console.WriteLine("The dog barks");
}
}
When a derived class is instantiated, the base class constructor is called first. You can explicitly call a base class constructor using the 'base' keyword:
class Animal
{
public Animal(string name)
{
Console.WriteLine($"Animal constructor: {name}");
}
}
class Dog : Animal
{
public Dog(string name) : base(name)
{
Console.WriteLine($"Dog constructor: {name}");
}
}
Inheritance respects access modifiers. Private members of the base class are not accessible in the derived class. Protected members are accessible within the derived class but not from outside.
Use the 'sealed' keyword to prevent a class from being inherited:
sealed class FinalClass
{
// This class cannot be inherited
}
ToString()
method for meaningful string representations.Inheritance is closely related to other OOP concepts in C#:
Understanding inheritance is crucial for designing robust and flexible C# applications. It forms the foundation for creating reusable and maintainable code structures.