Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 286
sharptooth Avatar asked Jun 28 '11 07:06

sharptooth


2 Answers

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.

like image 180
Marc Gravell Avatar answered Nov 03 '22 21:11

Marc Gravell


Can't inherit from more than one class as you know... really the only way is to do as you say and use interfaces. Or change programming language to one that supports multiple inheritance, but I'm sure that won't help!

like image 36
maddom Avatar answered Nov 03 '22 22:11

maddom