1

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

enter image description here

enter image description here

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?

Randy Hall
  • 7,716
  • 16
  • 73
  • 151
  • 1
    Does this answer your question? [What is the difference between == and Equals() for primitives in C#?](https://stackoverflow.com/questions/21273890/what-is-the-difference-between-and-equals-for-primitives-in-c) – phuclv Mar 23 '22 at 01:06

1 Answers1

8

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.

John Wu
  • 50,556
  • 8
  • 44
  • 80
  • 2
    +1. Might be worth pointing out that the debugger will display `object {int}` only in boxing scenarios. (or some weird override of `.ToString`) – Kirk Woll Mar 23 '22 at 00:58