James P. Wright
James P. Wright

Reputation: 9131

Multiple Constraint Types or check what type the Generic is?

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".

Upvotes: 0

Views: 149

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500515

You can use:

if (typeof(T) == typeof(EntityObject))

or

if (typeof(EntityObject).IsAssignableFrom(typeof(T)))

depending on your requirements. (See the docs for Type.IsAssignableFrom for 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).

Upvotes: 2

Chris Shain
Chris Shain

Reputation: 51329

There is no way to constrain for two unrelated types. You either need a common type (like an interface) or two versions of the constrained generic class.

Assuming T is unconstrained, you can use if (typeof(T).Equals(typeof(EntityObject))) { ... } to check whether T is of a certain type.

Upvotes: 0

Related Questions