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 t开发者_开发问答ype 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!
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))
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 ==
What's wrong with this?
if (!value1.Equals(value2))
Should be "cross object".. :)
Not all types have a default implementation of the ==
operator. For classes, the default ==
operation is to compare the references. For structs, no such default implementation exists.
You can add type constraints to generic type parameters in C#. Unfortunately, you can't define a constraint that forces the type to have an implementation of the ==
operator. The best you can do is to force the type to be a class: where T: class
. An article about type parameter constraints in C#
if you use value1.equals(value2) then you have a problem with null values. Better:
object.equals(value1,value2)
Or for reference types (be careful):
object.referenceEquals(value1,value2)
try
Equals(value1, value2)
A good way of avoiding null ref's
Another thing that you could do is define the comparison operator (actually, the difference operator here) to be able to compare elements of the type T. By itself, the compiler cannot really know what you mean when you write value1 != value2
, except if the operator has been defined previously.
To define an operator, you'd use
public operator!=(T a, T b) {
// Comparison code; returns true or false
}
精彩评论