Possible Duplicate:
Can’t operator == be applied to generic types in C#?
I've got the following generic class and the compiler complains that "Operator '!=' cannot be applied to operands of type 'TValue' and 'TValue'
" (see CS0019):
public class Example<TValue>
{
private TValue _value;
public TValue Value
{
get { return _value; }
set
{
if (_value != value) // <<-- ERROR
{
_value= value;
OnPropertyChanged("Value");
}
}
}
}
If I constrain TValue
to class
, I could use Object.Equals()
. Since I need this for boths structs and classes I'd be very happy if I could avoid that though.
So the question is, how can I compare two elements of the same but unconstrained generic type for equality?
Did you try something like this?
public class Example<TValue>
{
private TValue _value;
public TValue Value
{
get { return _value; }
set
{
if (!object.Equals(_value, value))
{
_value = value;
OnPropertyChanged("Value");
}
}
}
}
Three options:
IEquatable<TValue>
and then call x.Equals(y)
IEqualityComparer<TValue>
and use thatEqualityComparer<TValue>.Default
to perform the comparisonsYou could always mix and match options 2 and 3, of course - default to the default comparer, but also allow a specific one to be provided.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With