CAB201

icon picker
CAB Inheritance

C# Inheritance: A Quick Guide

Inheritance in C# is a mechanism where a new class inherits properties and methods from an existing class. It promotes code reuse and establishes a relationship between classes.

Types of Inheritance

1. Single Inheritance

In single inheritance, a class inherits from only one base class.
class Animal
{
public void Eat() { Console.WriteLine("Eating..."); }
}

class Dog : Animal
{
public void Bark() { Console.WriteLine("Barking..."); }
}

// Usage (make sure to have main method)
Dog myDog = new Dog();
myDog.Eat(); // Inherited method
myDog.Bark(); // Own method

2. Multilevel Inheritance

Multilevel inheritance involves a derived class inheriting from another derived class.
class Animal
{
public void Eat() { Console.WriteLine("Eating..."); }
}

class Mammal : Animal
{
public void Breathe() { Console.WriteLine("Breathing..."); }
}

class Dog : Mammal
{
public void Bark() { Console.WriteLine("Barking..."); }
}

// Usage (make sure to have main method)
Dog myDog = new Dog();
myDog.Eat(); // From Animal
myDog.Breathe(); // From Mammal
myDog.Bark(); // Own method

3. Hierarchical Inheritance

In hierarchical inheritance, multiple classes inherit from a single base class.
class Animal
{
public void Eat() { Console.WriteLine("Eating..."); }
}

class Dog : Animal
{
public void Bark() { Console.WriteLine("Barking..."); }
}

class Cat : Animal
{
public void Meow() { Console.WriteLine("Meowing..."); }
}

// Usage (make sure to have main method)
Dog myDog = new Dog();
myDog.Eat(); // From Animal
myDog.Bark(); // Own method

Cat myCat = new Cat();
myCat.Eat(); // From Animal
myCat.Meow(); // Own method

Key Points

Use the : symbol to define inheritance in C#
Inherited members can be accessed directly in the derived class
C# doesn't support multiple inheritance of classes, but it can be achieved through interfaces
The base keyword can be used to access members of the base class
Remember, inheritance should be used to model "is-a" relationships between classes. Overuse of inheritance can lead to complex and hard-to-maintain code, so use it judiciously.

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.