Is there a way to limit who can inherit a class or interface?

I wonder if there is a way to limit who can inherit from the class.

  • internal : does not allow class to inherit outside the assembly
  • sealed : class cannot be inherited

Is there a keyword or way to allow only certain classes (say, from my own namespace) to inherit this class?

In addition, I do not want this special class to be common. My concern is not safety, but the design as a whole.

An example of what I want:

  • Class A.
  • Class B inherits from A
  • Class C cannot inherit from A
+7
source share
2 answers

Is there a way to allow only certain classes to inherit this class?

Yes. If the inheriting code is partially trusted, you can place the inheritance requirement in the base class, and the runtime will not allow the inheritance class to load if it does not meet the demand conditions:

https://msdn.microsoft.com/en-us/library/x4yx82e6(v=vs.100).aspx

Of course, full trust means full trust. Fully trusted code can inherit whatever it wants.

I suspect that you are trying to introduce restrictions that you really should not try to impose. Can you describe why you are trying to do this difficult thing? Perhaps the best way to do what you want.

UPDATE:

I am trying to limit inheritance inside my classes in the same assembly.

Then you probably should have said that first.

Make all class constructors internal. To inherit from a class, it must have an accessible constructor. If you do all the internal constructors, then only the classes in this assembly can inherit the base class.

+16
source

As far as I know, using internal is the only way to control who can inherit the class. If the descendants must be in a different assembly, you can let classes from another assembly see the internal elements of your assembly using the InternalsVisibleTo attribute (the target assembly must be signed in order for this to work with signed assemblies).

+8
source

All Articles