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

I have a list defined as:

var Items = new List<IItem>(); 

Now there are several different classes that have this interface, and one of them is Consumable. The Consumable class is also overloaded with the == operator. Now I have the following code and it does not work:

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

This does not work. I set a breakpoint in the overload of the == operator, and it never reaches it. When I do phased debugging, item1 and item2 are of type Consumable, and GetType returns Consumable. I even try this code:

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

and the results of this equality are true. Now, if I try this:

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

and this causes a breakpoint in the overload of the == operator. Why would I have to manually transfer the variable if, during step-by-step debugging, it already thinks that they are both consumed? Is it because I pull them out of the IItems list?

+4
source share
4 answers

Since your list is List<IItem> , I assume you have something like:

 var item1 = Items[0]; 

or whatever; here item1 variable is introduced as IItem . Operator resolution occurs at build time through static analysis (not at run time through polymorphism / RTTI), so the only available == is the default value for any object , that is, reference equality.

To support your custom operator, you must enter the characters , eg:

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

Your roll reaches a similar thing.

Another option is to make sure that == and Equals (and GetHashCode() ) are consistent, and use:

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

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

+10
source

The total runtime of langauge only knows that your two objects implement the IItem interface. The smallest common part of the object hierarchy is System.Object. And you did not overload the == operator from System.Object.

To use the correct overload, you must specify the type of object.

+1
source

== does not check for equality of types, but for classes it checks for reference equality. Therefore, if the variables point to the same object, this will be true. For example, for example:

 var temp = item1; var temp2 = item1; if( temp == temp2 ) { //this code will execute } 
0
source

Shouldn't be IItem IComparable?

0
source

All Articles