I have a Base class that needs a Generic type. That can be either EntityObject or a custom type of mine.
I need a way to constrain the Base class to EITHER type and I also need a way to check if the Generic is of a certain type.
When I do if (T is EntityObject) or if (typeof(T) is EntityObject) it either says I am using T as a variable, or for typeof(T) I get that it “will never be of the given type”.
I have a Base class that needs a Generic type. That can be either
Share
You can use:
or
depending on your requirements. (See the docs for
Type.IsAssignableFromfor more details.)Of course, this is an execution-time check – you can’t have “one of…” constraints at compile time. Depending on your scenario, it may well be appropriate to have two differently named and constrained public methods which call one unconstrained private method (which “knows” you’ve got an appropriate type due to only being called from the public ones).