Inheritance in CSharp
Back to: C# .NET Tutorial
Inheritance is a foundational concept in C# that allows classes to acquire properties and behaviors from other classes. This article provides an in-depth understanding of inheritance with practical code examples to illustrate its application.
1. Single Inheritance
class Animal { public void Eat() { Console.WriteLine("Animal is eating."); } } class Dog : Animal { public void Bark() { Console.WriteLine("Dog is barking."); } }
2. Multilevel Inheritance
class Animal { public void Eat() { Console.WriteLine("Animal is eating."); } } class Mammal : Animal { public void Breathe() { Console.WriteLine("Mammal is breathing."); } } class Dog : Mammal { public void Bark() { Console.WriteLine("Dog is barking."); }
3. Hierarchical Inheritance
class Animal { public void Eat() { Console.WriteLine("Animal is eating."); } } class Cat : Animal { public void Meow() { Console.WriteLine("Cat is meowing."); } } class Dog : Animal { public void Bark() { Console.WriteLine("Dog is barking."); }
4. Benefits of Inheritance
- Code Reusability: Inherited code can be reused.
- Code Organization: Promotes a structured and modular codebase.
- Polymorphism: Allows for flexible use of derived classes.
Conclusion
Inheritance is a powerful feature in C# that enables code reuse, organization, and polymorphism. By mastering inheritance and its various forms, you can design efficient and structured code for your C# applications. The provided examples demonstrate the practical use of inheritance in C# programming.