Don't judge an Integer by its wrapper.
cmsimike.com
cmsimike.com
Now you have to carry around the fact that == sometimes isn't a reference comparison, even though that's what Java claims it always is?
Seems like a pretty poor design decision.
If I'm missing something basic, please correct away.
The problem is caused by him comparing objects as if they were primitives. The Integer class is basically just a wrapper around an "int" primitive. When an Integer object is initialized with a value between -128 and 127 it will return an object from an internal cache.
The second time he creates an Integer with the value of 127 it uses the cached object, which of course is identical to the previous one. When he tries this with 128, the cache is not used and a new Integer object is created.
tl;dr; Integer is an object where some values are cached to avoid creating a new object. The "==" operator compares the objects, and not the values they represent.
There is no wrapper class for "primitives" in C# though, to box it, you cast it to System.Object, and that allocates an object instance for you on the heap. To unbox, cast it to System.Int32.
'int' in C# is just an alias for System.Int32 though, so I guess there is no analogue to the Java situation in C#. You'd either be comparing System.Object references, or System.Int32 value types, not some hybrid.
Example:
using System;
class Boxing
{
static void Main(string[] args)
{
int i1 = 5;
object o1 = 5;
object o2 = 5;
int i2 = (int)o2;
Console.WriteLine("o1 == o2: {0}", o1 == o2);
Console.WriteLine("i1.Equals(o1): {0}", i1.Equals(o1));
Console.WriteLine("i2: {0}", i2);
}
}
Prints: o1 == o2: False
i1.Equals(o1): True
i2: 5