Why does this equality test fail?

Take the following class and unit test.

public class Entity
    {
        public object Id { get; set; }

        public override bool Equals(object obj)
        {
            return this == (Entity)obj;
        }

        public static bool operator == (Entity base1, Entity base2)
        {
            if (base1.Id != base2.Id)
            {
                return false;
            }

            return true;
        }

        public static bool operator != (Entity base1, Entity base2)
        {
            return (!(base1.Id == base2.Id));
        }
    }

        [TestMethod]
        public void Test()
        {
            Entity e1 = new Entity { Id = 1 };
            Entity e2 = new Entity { Id = 1 };
            Assert.IsTrue(e1 == e2); //Always fails
        }

Can someone explain why it fails?

+3
source share
8 answers

Since you are relying on an object reference for a comparator:

public object Id { get; set; }

Replace

    public static bool operator == (Entity base1, Entity base2)
    {
        if (base1.Id != base2.Id)
        {
            return false;
        }

        return true;
    }

FROM

    public static bool operator == (Entity base1, Entity base2)
    {
        return object.Equals(base1.Id, base2.Id);
    }
+3
source

The property Idis of type object. When you create two instances using 1 as the identifier for each of them, you will get two different objects in the box. Then you compare these objects using referential equality.

Proposed changes for correction:

  • Change type Idto type intif necessary.
  • object.Equals ==

, .

, , , , . :

  • GetHashCode, Equals.
  • Equals , , . , false.
  • ==

    return base1.Id == base2.Id;
    
  • ==
  • , != !(base1 == base2), , .
  • Equals . , (IMO - , , ).
+8

e1.Id e2.Id - . , , , base1.Id == base2.Id .

+2

equals - , . , , .

, Equals, :

http://weblogs.asp.net/tgraham/archive/2004/03/23/94870.aspx

Equals , , "" .

+2

- , int. == .

+2

Id .

1 ( int) , 1 . Id , base1.Id!= Base2.Id reference, value, . int Equals(), != .

+1

If you made your Idmember int, it will work. But, as CookieOfFortune said, when you compare two objects, it looks to see if they are the same object, and not if they have the same value.

0
source

Change the type of Id to int or another type of value. The problem is that you are comparing 2 objects which I assume is the problem that you overloaded the == operator to solve

0
source

Source: https://habr.com/ru/post/1709213/


All Articles