Search code examples
c#.netinheritancemultiple-inheritance

How to deal with CS1721 when I really need to inherit from two classes?


In my C# code I want a CustomIdentity class that inherits from System.MarshalByRefObject and System.Security.Principal.GenericIndentity classes.

However when I try to write such inheritance C# would object with CS1721 error saying I can't directly inherit from more than one class.

Now in this case it's quite easy to overcome this - I'll inherit from IIdentity, add GenericIdentity member variable and reimplement all IIdentity methods via that member variable.

But how would I do in case I wanted to inherit from two classes with a huge set of methods?


Solution

  • You don't. You can't.

    That is not supported in C# or .NET.

    You use multiple interface implementation, and at most single (non-object) inheritance. In most cases, even single inheritance is vastly overused ;p

    To absorb the methods, you'd have to use some kind of encapsulation. Extension methods also provide a way to share methods between types, for completeness.