0

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?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 3
    `if (!value.Equals(_currentValue))` – Johnathan Barclay Dec 02 '21 at 14:38
  • 1
    You can use a stack to pop and push the values if you want to maintain a history. – Demodave Dec 02 '21 at 14:45
  • The same issue like with `IComparable` [here](https://stackoverflow.com/q/69899514) – Guru Stron Dec 02 '21 at 15:00
  • Pro tip: The docs are quite good for .NET: https://learn.microsoft.com/en-us/dotnet/api/system.iequatable-1. If you look, the only member that interface has is the `Equals` method: https://learn.microsoft.com/en-us/dotnet/api/system.iequatable-1.equals – Flydog57 Dec 02 '21 at 15:20

2 Answers2

1

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))
Dmitry
  • 13,797
  • 6
  • 32
  • 48
1

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)) {
  ...
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215