C# Inheritance
Inheritance lets a class (the derived/child class) acquire fields and methods from another class (the base/parent class), promoting code reuse. In C#, inheritance is expressed with a colon, like `class Dog : Animal`.
Inheritance models an 'is-a' relationship โ a Dog is an Animal โ allowing shared behavior to live in one place while specialized behavior lives in the derived class.
class Derived : Base {
// additional members
}Base and derived classes
A derived class inherits all accessible members (not private) of its base class. It can add new members and use the ones inherited from the base class directly.
Calling base members
The `base` keyword lets a derived class call a constructor or method from its base class, useful when you want to extend rather than replace behavior.
using System;
class Animal {
public void Eat() {
Console.WriteLine("Eating...");
}
}
class Dog : Animal {
public void Bark() {
Console.WriteLine("Woof!");
}
}
class Program {
static void Main() {
Dog d = new Dog();
d.Eat();
d.Bark();
}
}Eating...
Woof!Dog inherits Eat() from Animal and also has its own Bark() method.
using System;
class Animal {
public Animal() {
Console.WriteLine("Animal created");
}
}
class Dog : Animal {
public Dog() : base() {
Console.WriteLine("Dog created");
}
}
class Program {
static void Main() {
Dog d = new Dog();
}
}Animal created
Dog createdbase() calls the parent class's constructor before the Dog constructor runs.
Key points
- Inheritance lets a class reuse fields and methods from a base class.
- The colon (:) syntax expresses inheritance, e.g. `class Dog : Animal`.
- The base keyword accesses base class members or constructors.
- C# only supports single inheritance for classes (one direct base class).
