What is Inheritance in C#?
Inheritance is one of the core concepts of Object-Oriented Programming (OOP). It allows a class (called the child or derived class) to inherit properties and methods from another class (called the parent or base class).
This means the child class gets all the features of the parent class, plus it can have its own unique features. Itโs like inheriting traits from your parents but adding your own style.
Why Use Inheritance?
- Promotes code reuse โ donโt repeat yourself.
- Helps organize code in a natural, hierarchical way.
- Enables polymorphism, where child classes can be treated as their parent type.
Basic Example
class Animal
{
public void Eat()
{
Console.WriteLine("Eating food");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Woof!");
}
}
class Program
{
static void Main()
{
Dog dog = new Dog();
dog.Eat(); // inherited from Animal
dog.Bark(); // own method
}
}
Here, Dog
inherits from Animal
. That means Dog
has access to Eat()
from Animal
, and also its own method Bark()
.
Key Points
- Use the
:
symbol to specify inheritance. - Child classes inherit all public and protected members of the parent.
- Private members of the parent class are not inherited.
Quiz: Test Your Knowledge
1. What symbol is used to indicate inheritance in C#?
2. Which class is the parent class in inheritance?
3. Which members are inherited by child classes?
4. If class Cat
inherits from Animal
, which method call is valid?
5. What happens if you create an object of the child class?