ILoggable

A place to keep my thoughts on programming

 Subscribe

geekblog
[at]
claassen [dot] net

Powered by Blogger

Saturday, December 27, 2008

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.

Labels: ,