The following doesn’t compile:
public void MyMethod<T>(T value)
{
if (value == default(T))
{
// do stuff
}
}
Error: Operator '==' cannot be applied to operands of type 'T' and 'T'
I can’t use value == null because T may be a struct.
I can’t use value.Equals(default(T)) because value may be null.
What is the proper way to test for equality to the default value?
To avoid boxing for
struct/Nullable<T>, I would use:This supports any
Tthat implementIEquatable<T>, usingobject.Equalsas a backup, and handlesnulletc (and lifted operators forNullable<T>) automatically.There is also
Comparer<T>.Defaultwhich handles comparison tests. This handlesTthat implementIComparable<T>, falling back toIComparable– again handlingnulland lifted operators.