2

While searching for the reason for using Interfaces in C#, I stumbled upon MSDN where it says:

By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes. In addition, you must use an interface if you want to simulate inheritance for structs, because they can't actually inherit from another struct or class.

But how does ,Interface simulate multiple inheritance. If we inherit multiple interfaces, still we need to implement the methods referred in the Interface.

Any code example would be appreciated !!

5
  • 1
    I believe author treats behavior as a declared behavior of a class, not as an implemented behavior Commented Dec 22, 2014 at 9:26
  • @SergeyBerezovskiy so in a practical sense, multiple inheritance is not possible as stated ?? Commented Dec 22, 2014 at 9:30
  • same MSDN msdn.microsoft.com/en-us/library/4taxa8t2(v=vs.110).aspx Commented Dec 22, 2014 at 9:31
  • 1
    Multiple inheritance isn't supported in C#. That's why interfaces. Commented Dec 22, 2014 at 9:32
  • multiple inheritance of classes is not supported but multiple implementation of interface is supported... Commented Dec 22, 2014 at 9:35

1 Answer 1

5

This works using delegation. You compose a class using other classes and forward ("delegate") method calls to their instances:

public interface IFoo
{
    void Foo();
}

public interface IBar
{
    void Bar();
}

public class FooService : IFoo
{
    public void Foo()
    {
        Console.WriteLine("Foo");
    }
}

public class BarService : IBar
{
    public void Bar()
    {
        Console.WriteLine("Bar");
    }
}

public class FooBar : IFoo, IBar
{
    private readonly FooService fooService = new FooService();
    private readonly BarService barService = new BarService();

    public void Foo()
    {
        this.fooService.Foo();
    }

    public void Bar()
    {
        this.barService.Bar();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.