Search code examples
c#genericsoperator-keywordkeywordtypeof

if(T is classname) is not working: T is a type, which is not valid in the given context


I want to check if generic type T is a Student class or whatever.

in If statement, I do this:

if (T is Student)
{
    // Do sth.
}

and it doesn't compile and says :

T is a type, which is not valid in the given context

I know the code below will work instead:

if (typeof(T) == typeof(Student))
{
    // Do sth.
}

But I just liked to use is keyword because it is makes my code more readable.

What is the reason of that error and is there any way to use is or not?


Solution

  • What is the reason of that error?

    The reason is that you are asking whether a certain Type is (or might be) something else than a of type Type. and the answer is clearly a NO.

    and is there any way to use is or not?

    Yes there is, but for that you would need an instance of the object like T myObject then you can ask

    if (myObject is Student)
    {
        // Do sth.
    }
    

    Imagine a realworld scenario, where you have a human named Peter. Peter is the instance of the type human. In your example you are trying to ask: "if human is a student ...". which is rather difficult to understand or in compiler language:

    not valid in the given context

    whereas asking "if Peter is a student.." sounds much more comprehensivly, even for a C# compiler ;)