Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does casting the same two numbers to Object make them not equal?

Tags:

c#

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

like image 844
santosh singh Avatar asked Nov 28 '22 10:11

santosh singh


1 Answers

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.

like image 160
marcind Avatar answered Dec 16 '22 03:12

marcind