Ruben Capote
Ruben Capote

Reputation: 324

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

Upvotes: 8

Views: 3891

Answers (5)

Ssithra
Ssithra

Reputation: 710

Just for my personal edification, I'd like to know more about the business context which make such a design choice desirable, since my first thougt at reading the title was "Oh, very very bad idea ! A base class is NEVER supposed to know anything (and worse : to rule) its derived classes".

Upvotes: 1

abatishchev
abatishchev

Reputation: 100258

// 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
{
}

Upvotes: 4

user541686
user541686

Reputation: 210437

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

Upvotes: 4

Stuti
Stuti

Reputation: 1638

You can make the class A abstarct and inherit it in any number of classes..

Upvotes: -1

Aviad P.
Aviad P.

Reputation: 32639

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.

Upvotes: 8

Related Questions