Test for equality to the default value

前端 未结 2 1201
灰色年华
灰色年华 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:44

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

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

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

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

提交回复
热议问题