Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a class unsealed internaly but sealed externaly?

Tags:

c#

.net

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)?

like image 309
Eric Anastas Avatar asked Nov 05 '10 02:11

Eric Anastas


People also ask

Can we override sealed class?

If you create a sealed class, it cannot be derived. If you create a sealed method, it cannot be overridden.

Can a sealed class be private?

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.

Can a sealed method be overridden?

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.

Should all classes be sealed C#?

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.


2 Answers

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();
    }
}
like image 54
BrokenGlass Avatar answered Sep 24 '22 10:09

BrokenGlass


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

like image 33
mqp Avatar answered Sep 25 '22 10:09

mqp