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)
{
}
}
To shed more light on the "PlayerMovement is a type but is used like a variable" error: This implies that you have a "PlayerMovement" class somewhere in your code. Otherwise you'd get a completely different error. It's generally OK to have classes, functions, and members sharing the same name.
It is called generics.
You can use IsAssignableFrom
method on Type
to check whether one Type
can be assigned to another.
if (typeof(MyEntity).IsAssignableFrom(typeof(T)))
Note: if you want that T
can only be MyEntity
or it's subclasses, you can define generic constraint, like this:
static void Test<T>() where T : MyEntity
{
}
And the code like Test<object>()
won't even compile
You can check IsAssignableFrom
with this code:
public static void F<T>()
{
var isAssignable = typeof(IEnumerable).IsAssignableFrom(typeof(T));
Console.WriteLine ("{0} is {1} IEnumerable", typeof(T).Name, isAssignable ? "" : "not");
}
Examples:
F<IList>(); //prints IList is IEnumerable
F<IEnumerable>(); //prints IEnumerable is IEnumerable
F<object>(); //prints object is not IEnumerable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With