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 seeingfalse(since the instances are not the same)To correctly compare these objects you could use
Object.Equals(i, j)ori.Equals(j). This will work because the actual runtime instance of the object will beInt32whoseEquals()method has the correct equality semantics for integers.