Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the == operator (defined for the concrete type) not used?

I have a list defined as:

var Items = new List<IItem>();

Now there are a number of different classes that have that interface and one of them is Consumable. The Consumable class also has the == operator overloaded. Now I have the following code and is not working:

if(item1 == item2)
{
    //code...
}

This does not work. I put a break point in the == operator overload and it never gets to it. When I go through line-by-line debugging, both item1 and item2 are of type Consumable, both GetType returns Consumable. I even try this code:

var temp = item1.GetType();
var temp2 = item2.GetType();
if (temp == temp2)
{
    //code...
}

and this equality results is true. Now if I try this:

if(((Consumable)item1) == ((Consumable)item2))
{
    //code...
}

and this triggers the break point in the == operator overload. Why would I have to manually cast the variable if when line-by-line debugging show it already thinks they are both consumable? Is it because I am pulling them from a list of IItems?

like image 465
ryanzec Avatar asked Dec 21 '22 14:12

ryanzec


1 Answers

Since your list is List<IItem>, I'm assuming you have something like:

var item1 = Items[0];

or whatever; here item1 the variable is typed as IItem. Operator resolution happens during build via static analysis (not at runtime via polymorphism/RTTI), so the only == available is the default for any object, i.e. reference equality.

To support your custom operator, the variables must be typed accordingly, for example:

Consumable item1 = ..., item2 = ...;

Your cast achieves a similar thing.

Another option would be to make sure that == and Equals (and GetHashCode()) are in agreement, and use:

if(Equals(item1, item2)) {...}

which will do null checks and then use your overridden Equals method. This then supports polymorphism, so it doesn't matter what the types are.

like image 133
Marc Gravell Avatar answered Mar 01 '23 11:03

Marc Gravell