nkoniishvt
nkoniishvt

Reputation: 2521

Implement a typed restricted property

Two classes: A & B, each of which have a MyProp property.

The MyProp property of A can only be of A type. The MyProp property of B can either be of A or B type.

To implement this I thought about creating an interface IBase containing a property MyProp of type IBase and make A & B implement it.

The problem in this case is that A could have a MyProp of type B, so it's not an option.

I could remove the MyProp property from the interface and create a type A property in A and IBase in B but I feel that it's not a proper solution because both types have a MyProp property that works the same way so I feel that the property should be handled higher in the hierarchy.

I thought also about a generic abstract base class that have a property MyProp of its generic type but for the B type the generic type would be an infinitely recursive type:

ABase<ABase<ABase<...>>>

Is there a proper way to achieve this in C#?

Edit: changed the name of the property so there's no confusion anymore

Upvotes: 0

Views: 64

Answers (1)

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 29985

I don't think this problem is likely to be solved nicely "at compile time" so to speak. But I think, you should make some common ancestor for A and B, make both properties of that type and control type validity in property setters by raising an exception on incorrect type detection.

If your code is properly tested, the fact, that the incorrect assignment can only be detected at runtime should not matter much.

Upvotes: 1

Related Questions