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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With