Test for equality to the default value

前端 未结 2 1197
灰色年华
灰色年华 2021-02-02 05:03

The following doesn\'t compile:

public void MyMethod(T value)
{
    if (value == default(T))
    {
        // do stuff
    }
}

相关标签:
2条回答
  • 2021-02-02 05:37

    What about

    object.Equals(value, default(T))
    
    0 讨论(0)
  • 2021-02-02 05:44

    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.

    0 讨论(0)
提交回复
热议问题