Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generic class where type must implement IEquatable

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading