There are many things here you need to learn.
First off, "==" is an equality comparison, not a reference comparison. That means that for value types it compares actual values, implicitly casting as needed (so your int value becomes a double temporarily).
Secondly
int
and
double
are value types, and that means that in order to compare them using ReferenceEquals they need to be "boxed" - which means that a copy of the value they hold is encapsulated in a temporary reference type class and located on the heap. The two boxed references are then compared and will always give
false
.
Even if you simplify the code, you will always get
false
:
public static void Main()
int x = 1;
Console.WriteLine(object.ReferenceEquals(x, x));
}
Even if you reduce it to it's most basic:
public static void Main()
{
Console.WriteLine(object.ReferenceEquals(666, 666));
}
You will always get false because the references to the boxed values are not the same.
ReferenceEquals will only ever give
true
for reference types (including strings) but even then, you will get strange results:
Console.WriteLine(object.ReferenceEquals("ABC", "ABC"));
Will give true, as will
string s1 = "ABC";
string s2 = "ABC;
Console.WriteLine(object.ReferenceEquals(s1, s2));
And so will
string s1 = "ABC";
string s2 = s1.Replace("X", "Y");
Console.WriteLine(object.ReferenceEquals(s1, s2));
but that's a special case due to string interning.
You really need to understand the difference between value and reference types to know what you are doing with your code! Have a look here:
Using struct and class - what's that all about?[
^] but don't worry if it's a bit advanced for you!