The override operator is

I am trying to override Equals so that it compares based on the identifier of the variable:

public class OrderID
{
    public string ID { get; private set; }

    public OrderID(string id)
    {
        ID = id;
    }

    public override bool Equals(object obj)
    {
        if (obj is OrderID)
        {
            return ((OrderID)obj).ID == ID;
        }
        else return false;
    }

    public override string ToString()
    {
        return ID;
    }
}

However, when I test this as follows, it returns false:

static void Main(string[] args)
{

    OrderID i1 = new OrderID("Hello");
    OrderID i2 = new OrderID("Hello");

    bool test = i1 == i2;

    Console.WriteLine(test.ToString());
    Console.ReadKey();
}

What is the problem? When I try to get through this, my redefinition has not even entered.

+3
source share
3 answers

The Equals () method object is not the same as the '==' operator. You will need to overload the operator '==' for your type or call i1.Equals(i2)instead i1 == i2.

MSDN Guidelines for Overloading Equals () and Operators ==

+11
source

operator == , i1 i2 ( ). operator == , .

:

bool test = i1.Equals(i2);

.Equals ID operator == ID

if (obj is OrderID)
{
  return ((OrderID)obj).ID.Equals(ID);
}

ReferenceEquals. , Equals

+2

As mentioned, use i1.Equals(i2)for comparison. Also, remember that you must override GetHashCode()Equals when overriding, otherwise your class may not work as expected.

0
source

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


All Articles