jlipstate
jlipstate

Reputation: 141

Using Generic Types with As operator

I get a compiler error when Trying to use a generic with as. Since i can't do it the way I want to, what is a better way..? I wanted to check through 5-6 types, figuring i can use one method and see if it is null or not.

    T CheckIsType<T>(Thing thing)
    {
        return thing as T;
    }

exact error text:

Error   1   The type parameter 'T' cannot be used with     the 'as' operator because it does not have a class type     constraint nor a 'class' constraint.

Upvotes: 1

Views: 2432

Answers (3)

Daniel A. White
Daniel A. White

Reputation: 190907

I think you want to use is instead.

 var isAThing = thing is Thing;

Upvotes: 1

Andrew Cooper
Andrew Cooper

Reputation: 32576

Just add the constraint it's complaining about not being there:

T CheckIsType<T>(Thing thing)
    where T: class
{
    return thing as T;
}

Upvotes: 9

BradleyDotNET
BradleyDotNET

Reputation: 61339

as doesn't work with value types (like int) which T can be.

In this case, you just need a generic type parameter:

T CheckIsType<T>(Thing thing) where T: class
{
   return thing as T;
}

Upvotes: 3

Related Questions