ILoggable

A place to keep my thoughts on programming

December 27, 2008 geek ,

Comparison with default(T)

I was working on a generic class that I had limited to where : class because I wanted to use null as valid return value. Well, then I needed to use the class on Guid, which is a value type. So I replaced all return null with return default(T). That was fine except for my Enumerator which used null to yield break out of the iteration. Unfortunately

  if(t == default(T)) {
    yield break;
  }

wasn’t legal either. Then i thought, how about

  if(t.Equals(default(T))) {
    yield break;
  }

which compiles just fine, but of course throws a NullArgumentException, since I am after all looking for a null value.

After some digging I finally came across the solution:

  if(Comparer<T>.Default.Compare(t, default(T)) == 0) {
    yield break;
  }

and that did the trick.

2 to “Comparison with default(T)”

  1. LogicalError says...

    In case your generic class/method does not accept value types, then you could also use Object.ReferenceEquals(myObject,null)

  2. fre0n says...

    You could use:

    object.Equals(t, default(T))

Leave a comment