I have following code snippet but I am getting wrong output.
class Program
{
static void Main(string[] args)
{
var i = 10000;
var j = 10000;
Console.WriteLine((object) i == (object) j);
}
}
I was expecting true but I am getting false
You are boxing the numbers (via the object cast) which creates a new instance for each variable. The ==
operator for objects is based on object identity (also known as reference equality) and so you are seeing false
(since the instances are not the same)
To correctly compare these objects you could use Object.Equals(i, j)
or i.Equals(j)
. This will work because the actual runtime instance of the object will be Int32
whose Equals()
method has the correct equality semantics for integers.
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