Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a class A in C#, where A can only be inherited by B, C, D?

There is some mechanism to allow a class to be inherited by N classes only in C#?

like image 844
Ruben Capote Avatar asked Jun 15 '11 04:06

Ruben Capote


3 Answers

You may put it and it's derived classes in a separate assembly, and declare the constructor of the base class as internal. That way although you could inherit from it in a different assembly, but you wouldn't be able to instantiate any derived class.

like image 174
Aviad P. Avatar answered Sep 18 '22 14:09

Aviad P.


No, but you can always make the constructor throw an exception if it exceeds the limit.

like image 35
user541686 Avatar answered Sep 20 '22 14:09

user541686


// can be inherited only by classes in the same assembly
public abstract class A
{
    protected internal A() { }
}

// can't be inherited
public sealed class B : A
{
}
like image 41
abatishchev Avatar answered Sep 22 '22 14:09

abatishchev