I need to check if a generic type parameter T is MyEntity or a subclass of it.
Code below causes this compiler error:
'T' is a 'type parameter' but is used like a 'variable'
how to fix?
public class MyEntity { }
static void Test<T>()
{
// Error 34 'T' is a 'type parameter' but is used like a 'variable'
if (T is MyEntity)
{
}
}
You can use
IsAssignableFrommethod onTypeto check whether oneTypecan be assigned to another.Note: if you want that
Tcan only beMyEntityor it’s subclasses, you can define generic constraint, like this:And the code like
Test<object>()won’t even compileYou can check
IsAssignableFromwith this code:Examples: