0

I have one class which is already inherits with base class and i need to use some function from another abstract class. how to do that because a class can not inherit more than one class.

public Class ABC : BaseClass, SomeAbstractClass
{
}

need to have above functionality. can someone please help me out to do this in c#.

kattui
  • 19
  • 4

2 Answers2

1

You can't. Unlike C++, C# does not support multiple base classes.

What you can do is inherit the abstract class, and implement an interface that have been extracted from the base class - and instead of inherit from the base class, have a field of it's type (in short, use composition over inheritance):

public Class ABC : SomeAbstractClass, IBaseClass
{
    private IBaseClass _base;

    // initialize the IBaseClass in your constructor:

    public ABC(int a, string b)
        : base(a) // assume a constructor that takes an int on the abstract class
    {
        _base = new BaseClass(b); // assume a constructor that takes a string on the base class
    }

    // or a constructor for Dependency Injection:
    public ABC(int a, IBaseClass baseClass)
        : base(a)
    {
         _base = baseClass;
    }

    // implement the interface like this:

    public int SomeIBaseClassMethod(string a, int b)
    {
        return _base.SomeBaseClassMethod(a, b);
    }

    public bool IsValid 
    {
        get {return _base.IsValid;} 
        set {_base.IsValid = value}
    }
}
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
0

Multiple inheritance is not supported in C#. What you can do is implement different interfaces.

public class ABC: BaseClass, ISomeOtherInterface {

}
Peter Schneider
  • 2,879
  • 1
  • 14
  • 17
  • so how to use SomeAbstractClass inside an interface? – kattui Apr 03 '19 at 08:56
  • This [SO entry](https://stackoverflow.com/questions/178333/multiple-inheritance-in-c-sharp) describes the usage of multiple interfaces... – Peter Schneider Apr 03 '19 at 09:01
  • @PeterSchneider - the point is, they can't just instantiate the abstract class and wrap it or anything else like that. A better suggestion would be to inherit from the abstract class (which has to be inherited from anyway to be useful) and wrap a `BaseClass` instance. – Damien_The_Unbeliever Apr 03 '19 at 09:06