Eric Anastas
Eric Anastas

Reputation: 22223

Can I make a class unsealed internally but sealed externally?

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

Upvotes: 7

Views: 1196

Answers (3)

mqp
mqp

Reputation: 71995

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.

Upvotes: 6

JD Stuart
JD Stuart

Reputation: 557

You can also try doing something like this.

internal class InternalExtendible
{
    public string MyProperty { get; set; }
}

public sealed class ExternalSealedClass : InternalExtendible
{
}

Create an Internal class and create a public empty class that inherits from the internal class. When referencing the dll, only the public class will be visible to the user, but all the functionality of the internal class will be exposed.

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160962

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();
    }
}

Upvotes: 10

Related Questions