Generics, comparing (T == null)

I made a class using generics and I have a method like this

public bool Insert(T Item)
{
if (T == null)
{
throw new System.Exception();
}
// other code goes here
}

So if my T is a struct, will the compiler still generate the code to compare T to null or not




Answer this question

Generics, comparing (T == null)

  • John Shuttleworth

    Marking as answer. (Conclusion: use item == null, compiler evals to false for value types, and subsequently optimizes it away).
  • FernanPa

    That was my assumption too - in fact, I didn't even notice that typo until you pointed it out

  • Dundealing

    Surely that should be: "if (item==null)"


  • emkay

    Yes, but it will always evaluate to false for value types.

    HTH,
    Kent


  • Larry Beck

    sorry for the typo...

    I know it does generate (Item == null) in PE format, but will it still be there after the compiler produces native code It seems that the compiler could do some optimizations by eliminating the comparison for structs.



  • Generics, comparing (T == null)