In C# Is there way to specify a class to be inherited only by a class present in the same assembly and for other assemblies should behave like a public sealed type.
No. There is no such provision in the C# language itself. However, workarounds -- as suggested by others here -- may suffice.
The language itself doesn't have anything that makes this easy, but you should be able to do this by making your constructors internal. If you do this, however, you won't be able to new it up from external assemblies, so you'll have to add a factory method.
public class Foo
{
internal Foo()
{
}
public Foo Create()
{
return new Foo();
}
}
Here's an alternative that lets you new up the class in external assemblies
public sealed class Foo : FooBase
{
}
public class FooBase
{
internal FooBase() { }
}
One question you might ask yourself, however, is exactly why you want the class to be sealed. Sometimes it's inevitable, but I have seen the sealed
keyword get abused so often that I thought I'd bring it up. Often, developers will seal classes because they are overprotective of their code. Most of the time, if a class is well designed, it doesn't need to be sealed.
If your class is abstract, there's a very simple way to do it:
public abstract class Foo {
internal abstract void DoNothing();
// ... other members
}
Now although your class and most members are public, the internal abstract member makes it impossible to derive from the class outside your assembly.
You can't do that with language constructs, but try with reflection
public class MyClass{
public MyClass(){
if(this.GetType().Assembly != typeof(MyClass).Assembly){
throw new Exception("Can't derive from this type!");
}
}
Checked it up. Seems to be working. The only problem is that unless somebody reads documentation, the trouble is known at runtime.
The only way I can think would be to use a public wrapper on an internal class, probably with a common interface:
public interface IFoo
{
}
internal class Foo : IFoo
{
}
public sealed class PublicFoo : IFoo
{
private Foo m_Foo = new Foo();
}
public abstract class Foo
{
protected internal Foo()
{
}
public static Foo Create() { return new Foo(); }
}