Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for value equality between two interface instances in c#?

So I have an interface, lets call it IInterface.

public interface IInterface : IEquatable<IInterface>
{
    string Name { get; set; }
    int Number { get; }
    Task<bool> Update();
}

Then I try and implement the interface in Implementation.

    public bool Equals(IInterface other)
    {
        if (other == null) return false;

        return (this.Name.Equals(other.Name) && this.Number.Equals(other.Number));
    }

    public override int GetHashCode()
    {
        return this.Number.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        var other = obj as IInterface ;
        return other != null && Equals(other);
    }

    public static bool operator ==(Implementation left, IInterface right)
    {
        if (ReferenceEquals(left, right)) return true;

        if (ReferenceEquals(left, null)) return false;

        return left.Equals(right);
    }

    public static bool operator !=(Implementation left, IInterface right)
    {
        return !(left == right);
    }

The problem I am running into is in a setter:

    public IInterface MyIntf
    {
        get { return _myIntf; }
        set
        {
            if (_myIntf == value) { return; }
            _myIntf = value;
        }

Intellisense is showing that the equality test there is testing the references only and treating both left and right as objects. I assume this is because there is no operator overload for ==(IInterface left, IInterface right). Of course, I cannot actually implement that function because == requires one of the sides to match the type of the implementing class. How does one properly make sure two interfaces can be checked for equality against each other?

Update

Got it, you cannot implement == for an interface. I will use Equals. Thanks everyone.

like image 613
bodangly Avatar asked Apr 24 '16 20:04

bodangly


2 Answers

You should explicitly call Equals:

if (_myIntf != null && _myIntf.Equals(value)) { return; }

Implementing IEquatable<T> does not impact the == operator.

like image 183
Ondrej Tucny Avatar answered Nov 10 '22 21:11

Ondrej Tucny


Use Equals instead of ==:

public IInterface MyIntf
{
    get { return _myIntf; }
    set
    {
        if (_myIntf.Equals(value)) { return; }
        _myIntf = value;
    }
}
like image 44
MarcinJuraszek Avatar answered Nov 10 '22 19:11

MarcinJuraszek