How can I create a class A in C # where A can only inherit B, C, D?

Is there some mechanism that allows a class to be inherited by N classes only in C #?

+5
source share
5 answers

You can put it and its derived classes in a separate assembly and declare the constructor of the base class as internal . Thus, although you could inherit it in another assembly, you could not create an instance of any derived class.

+7
source

No, but you can always force the constructor to throw an exception if it exceeds the limit.

+4
source
 // can be inherited only by classes in the same assembly public abstract class A { protected internal A() { } } // can't be inherited public sealed class B : A { } 
+3
source

For my personal guidance only, I would like to know more about the business context that makes such a design choice desirable since my first look at reading the title was "Oh, a very, very bad idea! The NEVER base class should know something (and worse: manage) its derived classes.

+1
source

You can make class A abstarct and inherit it in any number of classes.

-one
source

All Articles