Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit properties and behaviors from another class. In C#, you can implement inheritance using the class
keyword. Here's a simple tutorial on inheritance in C# with examples of different types of inheritance.
1. Basic Inheritance:
using System;// Base classclass Animal{public void Eat(){Console.WriteLine("Animal is eating.");}public void Sleep(){Console.WriteLine("Animal is sleeping.");}}// Derived classclass Dog : Animal{public void Bark(){Console.WriteLine("Dog is barking.");}}class Program{static void Main(){// Creating an instance of the derived classDog myDog = new Dog();// Accessing methods from the base classmyDog.Eat();myDog.Sleep();// Accessing methods from the derived classmyDog.Bark();}}
In this example, Dog
is a derived class that inherits from the Animal
base class. The Dog
class can access the methods (Eat
and Sleep
) from the Animal
class.
2. Types of Inheritance:
a. Single Inheritance:
// Base classclass Animal{public void Eat(){Console.WriteLine("Animal is eating.");}}// Derived classclass Dog : Animal{public void Bark(){Console.WriteLine("Dog is barking.");}}class Program{static void Main(){Dog myDog = new Dog();myDog.Eat(); // Accessing base class methodmyDog.Bark(); // Accessing derived class method}}
b. Multiple Inheritance (through Interfaces):
// Interface 1interface IAnimal{void Eat();}// Interface 2interface IDog{void Bark();}// Derived class implementing multiple interfacesclass Dog : IAnimal, IDog{public void Eat(){Console.WriteLine("Dog is eating.");}public void Bark(){Console.WriteLine("Dog is barking.");}}class Program{static void Main(){Dog myDog = new Dog();myDog.Eat(); // Accessing method from Interface 1myDog.Bark(); // Accessing method from Interface 2}}
In C#, multiple inheritance is achieved through interfaces. The Dog
class implements both IAnimal
and IDog
interfaces.
Conclusion:
Inheritance is a powerful mechanism that promotes code reuse and helps in building a hierarchy of classes. It allows you to create a base class with common functionality and then derive specialized classes from it. Understanding the different types of inheritance and how to use them is essential for effective object-oriented programming in C#.