How to achieve multiple inheritance in C#

Multiple inheritance is a concept in object-oriented programming (OOP) that allows a class to inherit from multiple parent classes. However, C# does not directly support multiple inheritance due to the complexities and difficulties in managing multiple class inheritance. Instead, C# provides alternative mechanisms to achieve similar goals.

Solutions in C#

  1. Interfaces:

    • C# allows a class to implement multiple interfaces. Interfaces only contain method declarations, not implementations, which helps avoid the issues that come with multiple inheritance.

    public interface IFlyable
    {
        void Fly();
    }
    
    public interface ISwimmable
    {
        void Swim();
    }
    
    public class Duck : IFlyable, ISwimmable
    {
        public void Fly()
        {
            Console.WriteLine("Duck is flying.");
        }
    
        public void Swim()
        {
            Console.WriteLine("Duck is swimming.");
        }
    }
  2. Composition:

    • Instead of inheriting from multiple classes, you can create component objects within your class and use them to achieve the desired functionality.

    public class Engine
    {
        public void Start() 
        {
            Console.WriteLine("Engine started.");
        }
    }
    
    public class Wheels
    {
        public void Roll()
        {
            Console.WriteLine("Wheels are rolling.");
        }
    }
    
    public class Car
    {
        private Engine _engine = new Engine();
        private Wheels _wheels = new Wheels();
    
        public void Drive()
        {
            _engine.Start();
            _wheels.Roll();
            Console.WriteLine("Car is driving.");
        }
    }
  3. Mixin Pattern:

    • A mixin is a design pattern in which functionality from other classes is "mixed" into the main class using composition or extension methods.

    public class Animal
    {
        public void Eat()
        {
            Console.WriteLine("Animal is eating.");
        }
    }
    
    public class Bird
    {
        public void Fly()
        {
            Console.WriteLine("Bird is flying.");
        }
    }
    
    public class FlyingAnimal
    {
        private Animal _animal = new Animal();
        private Bird _bird = new Bird();
    
        public void Eat()
        {
            _animal.Eat();
        }
    
        public void Fly()
        {
            _bird.Fly();
        }
    }

Last updated