Does C# support Multiple Inheritance? How can you implement multiple inheritance in C#?

No, C# does not support multiple inheritance in the traditional sense, where a class can directly inherit from multiple base classes. This means a C# class can only have a single direct base class.

C# support inheritance by using multiple Interfaces. This is an alternative way of multiple inheritance.

However, C# supports multiple inheritance through interfaces. An interface in C# is a contract that defines a set of abstract methods and properties that a class must implement. A class can implement multiple interfaces, effectively achieving multiple inheritance of behavior.

Here's how you can implement multiple inheritance in C# using interfaces:

csharp
// First Interface interface IFlyable { void Fly(); } // Second Interface interface ISwimmable { void Swim(); } // Class implementing multiple interfaces class Bird : IFlyable, ISwimmable { public void Fly() { Console.WriteLine("Bird is flying."); } public void Swim() { Console.WriteLine("Bird is swimming."); } } class Fish : ISwimmable { public void Swim() { Console.WriteLine("Fish is swimming."); } } class Program { static void Main() { Bird bird = new Bird(); bird.Fly(); // Output: Bird is flying. bird.Swim(); // Output: Bird is swimming. Fish fish = new Fish(); fish.Swim(); // Output: Fish is swimming. } }

In this example, we have two interfaces, IFlyable and ISwimmable, with abstract methods Fly() and Swim(), respectively. The Bird class implements both interfaces, effectively inheriting behavior from both interfaces. The Fish class only implements the ISwimmable interface.

By implementing multiple interfaces, the Bird class can behave as both a flying and a swimming entity, while the Fish class can only behave as a swimming entity. This demonstrates how C# achieves multiple inheritance-like behavior through interfaces.


 

Post a Comment

Previous Post Next Post