I wonder if there is a way to limit who can inherit from a class.
internal
: doesn't allow class to be inherited outside the assemblysealed
: class cannot be inheritedIs there a keyword or way to allow only certain classes (let's say from it's own namespace only) to inherit that class?
Also, I do not want this special class to be generic. My concern isn't security but the design in general.
Example of what I want:
You can prevent a class from being subclassed by using the final keyword in the class's declaration. Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method. An abstract class can only be subclassed; it cannot be instantiated.
You cannot restrict inheritance in javascript. If you have a public constructor function that initializes an object, any other object can use it to make a derived object.
Solution-1: Use the final keyword (from C++11) So, it'll not be inherited by any class. If you try to inherit it, the compiler will flash an error that “a final class cannot be used as a base class“. Note that you can create an object of the final class as show in the main() method here.
A subclass does not inherit the private members of its parent class.
A trick that is sometimes used is declaring private constructors. That way you can achieve:
public class A
{
private A(){}
// Here B can inherit from A
public class B : A{}
}
// This is not allowed
public class C : A{}
This comes with it's limitations because only classes declared inside of A can inherit from A. I find this trick very useful to do case distinctions.
Is there a way to allow only certain classes to inherit that class?
Yes. If the inheriting code is partially trusted then you can put an inheritance demand on the base class and the runtime will not allow the inheriting class to load if it does not meet the conditions of the demand:
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're trying to impose restrictions that you really should not be trying to impose. Can you describe why you're trying to do this difficult thing? There's probably a better way to do what you want.
UPDATE:
I'm trying to limit inheritance within my classes in the same assembly.
Then you probably should have said that in the first place.
Make all the constructors of the class internal. In order to inherit from a class, it must have an accessible constructor. If you make all the constructors internal then only classes in that assembly can inherit from the base class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With