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.
In case your generic class/method does not accept value types, then you could also use Object.ReferenceEquals(myObject,null)
You could use:
object.Equals(t, default(T))