'C# int equality operator unexpectedly false
This is a more broad question, with my specific example. The code that gets to this point is rather convoluted so I hope this is enough.
Under what circumstances in C# are two of the same ints not equal?
1005 == 1005 //false
specConversion started off as a passed string spec, where the type of y (a property on a class) was determined, and then spec was converted to that type as specConversion. This appears to be working as intended, as both vars have the same type at this point. I'm not certain any of that is even relevant to the initial question: why are these two int values not equal?
Solution 1:[1]
When the debugger displays this:
object {int}
that means it's an int that is boxed. A boxed value type is an object (specifically, a System.ValueType), which is a reference type. Each boxing results in a new object instance, meaning that they will not have reference equality, even if they have boxed the same value. The == operator, for reference types, tests reference equality, so in this case it will return false.
If you want value equality instead of reference equality, use Equals.
public class Program
{
public static void Main()
{
object a = 1;
object b = 1;
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b));
}
}
Output:
False
True
https://dotnetfiddle.net/eSuFVL
The other solution is to store your int values in actual int variables instead of objects, e.g. by using generics.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |


