Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 623
David Schmitt Avatar asked Dec 03 '08 11:12

David Schmitt


3 Answers

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");
            }
        }
    }
}
like image 132
Sergiu Damian Avatar answered Oct 23 '22 16:10

Sergiu Damian


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.

like image 43
Jon Skeet Avatar answered Oct 23 '22 15:10

Jon Skeet


  • Equals() for value types
  • ReferenceEquals() for reference types
like image 2
leppie Avatar answered Oct 23 '22 15:10

leppie