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: ,

2 Comments:

At 12:57 AM, Blogger LogicalError said...

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

 
At 11:02 AM, OpenID fre0n said...

You could use:

object.Equals(t, default(T))

 

Post a Comment

<< Home