Is it possible to make a class unsealed inside, but closed outside?

In C #, is it possible to create a class that can be obtained from the inside (unsealed), but then prevent others from accessing my library due to the inheritance of my open class (sealed)?

+6
c #
source share
3 answers

I assume that you could create an constructor for the internal class so that only other classes in your assembly can be extracted from them, if you still need to instantiate this class, you could provide a factory method to return the instances.

edit to add sample:

 public class MyFoo { internal MyFoo() { } public static MyFoo CreateFoo() { return new MyFoo(); } } 
+9
source share

Eric Lippert notes three ways to do this. tl; dr: do not seal your class, but include an internal abstract method in your class or make all internal or private constructors or use a PermissionSet to add metadata to the class.

http://blogs.msdn.com/b/ericlippert/archive/2008/09/26/preventing-third-party-derivation-part-one.aspx

http://blogs.msdn.com/b/ericlippert/archive/2008/10/06/preventing-third-party-derivation-part-two.aspx

+5
source share

You can also try to do something like this.

 internal class InternalExtendible { public string MyProperty { get; set; } } public sealed class ExternalSealedClass : InternalExtendible { } 

Create an inner class and create an open empty class that inherits from the inner class. When referencing a DLL, only the open class will be displayed, but all the functionality of the inner class will be shown.

0
source share

All Articles