Alex Rivera | Logout

How to compare two elements of the same but unconstrained generic type for equality?

Asked 2008-12-03T11:44:41.190
10

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?

Edit
Report

4 Answers

7

Three options:

  • Constrain TValue to implement IEquatable<TValue> and then call x.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.

answered 2008-12-03T12:47:40.003
2
  • Equals() for value types
  • ReferenceEquals() for reference types
answered 2008-12-03T11:48:26.330
1

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");
            }
        }
    }
}
answered 2008-12-03T12:39:28.897
0
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;
        }
answered 2011-07-14T10:17:20.043

Your Answer