1

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.
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
jlipstate
  • 131
  • 1
  • 9
  • 2
    why dont you just use `is`? – Daniel A. White Jun 16 '14 at 23:01
  • I was hoping to be able to use the variable instead of having to cast when it isnt null. (And seemed like a good chance to use generics for the first time outside of following Troelsen) – jlipstate Jun 16 '14 at 23:04
  • It is good idea to check MSDN first - [Compiler Error CS0413](http://msdn.microsoft.com/en-us/library/xxwdytdz.aspx)... – Alexei Levenkov Jun 16 '14 at 23:09
  • @sdiguana you are casting it with `as` – Daniel A. White Jun 16 '14 at 23:16
  • at least in my mind, this seems more efficient. otherwise i need to hard cast (or use as) when the is is true, after doing it multiple times with several types, the method above seems like less code. Perhaps it will turn out to e a bad idea, but meh, can only learn by doing it wrong a few times. (I do appreciate the guidance towards is no less, hopefully you dont mind that I'm going to try to stay with as for now). – jlipstate Jun 16 '14 at 23:21
  • Possible duplicate of [Operator as and generic classes](https://stackoverflow.com/questions/693463/operator-as-and-generic-classes) – Rudolf Dvoracek Sep 27 '17 at 12:43

3 Answers3

9

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

T CheckIsType<T>(Thing thing)
    where T: class
{
    return thing as T;
}
Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
3

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;
}
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
1

I think you want to use is instead.

 var isAThing = thing is Thing;
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445