Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for equality to the default value

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?

like image 288
Greg Avatar asked Dec 13 '09 06:12

Greg


People also ask

How can we set default value to the variable?

You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.

What is return default in C#?

The default keyword returns the "default" or "empty" value for a variable of the requested type. For all reference types (defined with class , delegate , etc), this is null . For value types (defined with struct , enum , etc) it's an all-zeroes value (for example, int 0 , DateTime 0001-01-01 00:00:00 , etc).


2 Answers

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.

like image 112
Marc Gravell Avatar answered Sep 26 '22 08:09

Marc Gravell


What about

object.Equals(value, default(T)) 
like image 21
Graviton Avatar answered Sep 25 '22 08:09

Graviton