Home > Mobile >  Generic class where type must implement IEquatable
Generic class where type must implement IEquatable

Time:12-03

I'm trying to create a generic "property" class that maintains both it's current value and the last value.

public class GenericTrackingProperty<T> where T : IEquatable<T>
{
    private T _oldValue;
    private T _currentValue;

    public T Value
    {
        get { return _currentValue; }
        set
        {
            if (value != _currentValue)
            {
                _oldValue = _currentValue;
                _currentValue = value;
            }
        }
    }
}

Despite the use of the where in the class definition to ensure the generic type is equatable the compiler complains about the comparison "if (value != _currentValue" giving an error "Operator '!=' cannot be applied to operands of type 'T' and 'T'". What am I doing wrong?

CodePudding user response:

IEquatable<T> doesn't contain operators, but it contains the Equals method.
Use it instead of the equality operator:

if (!value.Equals(_currentValue))

Or, null-aware:

if (value == null ? _currentValue == null : !value.Equals(_currentValue))

CodePudding user response:

Let .NET compare both values for you (while checking for null etc):

if (!EqualityComparer<T>.Default.Equals(value, _currentValue)) {
  ... 
}

You can use value.Equals but in this case you have to check for null:

if (value == null && _currentValue != null || !value.Equals(_currentValue)) {
  ...
}
  • Related