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: Operato
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)
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
}
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))
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#
try
Equals(value1, value2)
A good way of avoiding null ref's