Test for equality to the default value

C#GenericsEquality

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

To avoid boxing for struct / Nullable<T>, I would use:

if (EqualityComparer<T>.Default.Equals(value,default(T)))
{
    // do stuff
}

This supports any T that implement IEquatable<T>, using object.Equals as a backup, and handles null etc (and lifted operators for Nullable<T>) automatically.

There is also Comparer<T>.Default which handles comparison tests. This handles T that implement IComparable<T>, falling back to IComparable - again handling null and lifted operators.

Solution 2 - C#

What about

object.Equals(value, default(T))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGregView Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#GravitonView Answer on Stackoverflow