0

Ive the following code:

    TConverted ret;
    ret = forward.Get<TConverted>(GetForwardKey(id, convType));
    if (ret != default(TConverted))... // wrong here !

the generic Get function returns an item from a cache. It can be a value type or a class. I would like to check if the returned value is null or the default, but the code I guess it should work it does not. Is it possible to do?

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115

1 Answers1

3

From this essentially-identical question...

To avoid boxing, the best way to compare generics for equality is with EqualityComparer<T>.Default. This respects IEquatable<T> (without boxing) as well as object.Equals, and handles all the Nullable<T> "lifted" nuances. Hence:

if(EqualityComparer<T>.Default.Equals(obj,default(T)) {
    return obj;
}

This will match:

  • null for classes
  • null (empty) for Nullable<T>
  • zero/false/etc for other structs

If this is helpful to you, please upvote Mark Gravell's answer (which I've quoted) on the question I linked to.

Community
  • 1
  • 1
Chris
  • 4,661
  • 1
  • 23
  • 25