Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't compare T value1 with T value2 = default(T). Why and how to do that on C#?

I'm trying the following:

T value1 = el.value; // it's of type T already
T value2 = default(T);
if (value1 != value2) // gives the following error: Operator '!=' cannot be applied to operands of type 'T' and 'T'
{
    // ...
}

So, how could I compare both values? And why do this error occur?

Thanks in advance!

like image 290
Girardi Avatar asked Jan 28 '11 19:01

Girardi


2 Answers

You can either use a constraint of where T : IEquatable<T> as Henk mentioned, or ignore constraints and use:

if (!EqualityComparer<T>.Default.Equals(value1, value2))
like image 85
Jon Skeet Avatar answered Dec 01 '22 02:12

Jon Skeet


Your surrounding generic class should list a constraint: T : IEquatable<T>

And then you have to use value1.Equals(value2)

The reason for all this is that not all types define operator ==

like image 35
Henk Holterman Avatar answered Dec 01 '22 04:12

Henk Holterman