Reputation: 2200
If I have 3 classes as follows:
abstract class A {}
public class B : A {}
public class C: A {}
I want to force other code to use B or C directly, or inherit from either B
or C
. I don't want other code to inherit directly from A
.
Is this even possible?
A
cannot be private since B
and C
must be public, making A private would cause "Inconsistent accessibility". A
can't be internal
for the same reason.
Why do I want this?
I have designed an API, the response of which must include either property x, or both properties y & z, but not all 3. It also includes a bunch of other properties that are common to both possibilities. i.e. -
{
"allOf": [
{
"type": "object",
"properties": {
"w": { ... }
}
},
{
"anyOf": [
{
"type": "object",
"properties": {
"x": { ... }
}
},
{
"type": "object",
"properties": {
"y": { ... },
"z": { ... }
}
}
]
}
]
}
Upvotes: 0
Views: 256
Reputation:
If you make B
and C
part of A
you can mark the constructor of A
private
so no other classes can inherit directly from A
:
public class A
{
private A()
{
}
public class B: A
{
public B()
{
}
}
public class C: A
{
public C()
{
}
}
}
The downside however is that you now have to refer to B
as A.B
(see edit, this is not needed), but functionality wise the rest of the application is able to instantiate and use classes of type A.B
and A.C
and inherit from them while prohibiting the ability to instantiate or use A
directly (even in the same file/assembly).
So this is invalid anywhere outside of A
:
public class D: A
{
}
But this you can use anywhere:
public class E : A.B
{
}
Edit: As noted by Jonathan Barclay you prevent having to use A.B
by the following using directive, which will allow you to inherit as normal:
using static MyNamespace.A;
public class D : B
{
}
Upvotes: 3