How to compare two elements of the same but unconstrained generic type for equality? [duplicate]
Question
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?
Solution
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");
}
}
}
}
OTHER TIPS
Three options:
- Constrain TValue to implement
IEquatable<TValue>
and then callx.Equals(y)
- Take another parameter of type
IEqualityComparer<TValue>
and use that - Use
EqualityComparer<TValue>.Default
to perform the comparisons
You 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.
- Equals() for value types
- ReferenceEquals() for reference types
Is IComparable an option?
public class Example<TValue> where TValue: IComparable
{
private TValue _value;
public TValue Value
{
get { return _value; }
set
{
if (_value.CompareTo(value) != 0)
{
_value = value;
OnPropertyChanged("Value");
}
}
}
}
I think the !=
operator cannot be applied here because there are cases where it can't be used. For instance, !=
can't be used for comparing structs, unless the compare operators (==
!=
) are overloaded.
Of course, you can compare language structs, like int != int
, but I'm not sure how this is implemented.
So, because TValue can be a custom struct, it cannot use the !=
operator.
public static bool operator ==(EntityBase<T> entity1, EntityBase<T> entity2)
{
if ((object)entity1 == null && (object)entity2 == null)
{
return true;
}
if ((object)entity1 == null || (object)entity2 == null)
{
return false;
}
if (Comparer<T>.Default.Compare(entity1.Id, entity2.Id) != 0)
{
return false;
}
return true;
}