In C# is it possible to make a class that can be derived from internally (unsealed), but then prevent other people referencing my library externally from inheriting from my public class (sealed)?
If you create a sealed class, it cannot be derived. If you create a sealed method, it cannot be overridden.
No, a sealed class cannot be declared private explicitly. In fact, any class defined in a namespace cannot be explicitly declared as private, protected, protected internal, or private protected.
Sealed class cannot be inherited and sealed method in C# programming cannot be overridden. If we need to stop a method to be overridden or further extension of a class in inheritance hierarchy, we need to use Sealed method and Sealed class respectively in C# object oriented programming.
The C# keyword sealed and the VB.NET keyword NotInheritable must be specified explicitly. Since there is no compiler warning most developers don't bother to seal their classes. Hence most classes are not properly designed for inheritance but are implicitly declared as inheritable.
I suppose you could make the constructor of the class internal
so that only other classes in your assembly could derive from them, if you still need to create instances of that class you could provide a factory method to return instances.
edit to add a sample:
public class MyFoo
{
internal MyFoo()
{
}
public static MyFoo CreateFoo()
{
return new MyFoo();
}
}
Eric Lippert notes three ways to do this. tl;dr: don't seal your class, but include an internal abstract method in your class, or make all the constructors internal or private, or use the PermissionSet
attribute to add metadata to the class.
Link
Link
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