Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fix 'T' is a 'type parameter' but is used like a 'variable' compile error

Tags:

c#

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)
    {
    }
}
like image 773
Andrus Avatar asked Jan 13 '13 10:01

Andrus


People also ask

Is a type but used as a variable C#?

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.

Which one of the following options is the correct name for empty type parameter?

It is called generics.


1 Answers

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
like image 113
Ilya Ivanov Avatar answered Oct 04 '22 16:10

Ilya Ivanov