Search code examples
c#.netinterfacemultiple-inheritance

Interface vs Multiple Inheritance In C#


I have a set of Class A and Class B both have Some properties. and another Class C which has their own properties.

Whenever i create a instance of class C i want to access all properties of all three classes with objClassC.

How can i Achieve this in C#?

I m facing two problem :-

  1. I can not inherit both the classes A, B in Class C (C# doesn't Support Multiple Inheritance)
  2. if i use Interface instead of Class A, B (In Interface we can not Contains Fields)

Solution

  • Why don't you contain instance of Class A and Class B inside Class C. Use Composition

    class C
    {
    //class C properties
    public A objA{get;set;}
    public B objeB{get;set;}
    }
    

    Then you can access

    C objc = new C();
    objc.objA.Property1 = "something";
    objc.objB.Property1 = "something from b";
    

    check out the article Composition vs Inheritance

    EDIT:

    if i use Interface instead of Class A, B (In Interface we can not Contains Fields)

    Well, interfaces can't contain fields, if you define one, you will get compilation error. But interfaces can contain properties with the exception that you can't specify the access specifiers, as all elements of the interface are considered public. You can define properties for Interface 'A' and 'B' as:

    public interface IA
    {
         int Property1 { get; set; }
    }
    
    
    public interface IB
    {
        int Property2 { get; set; }
    }
    

    Then you can implement them in the class C like:

    public class C : IA, IB
    {
        public int Property1 { get; set; }
        public int Property2 { get; set; }
    }
    

    Later you can use them as:

    C objC = new C();
    objC.Property1 = 0;
    objC.Property1 = 0;