Why is Int32.Equals(Int16) always false?

  • Thread starter Thread starter John Mark Howell
  • Start date Start date
J

John Mark Howell

Why is Int32.Equals(Int16) always false?
The following code:
<code>
Int32 a = 123;
Int16 b = 123;
if (a.Equals(b))
Console.WriteLine("a.Equals(b) is true");
else
Console.WriteLine("a.Equals(b) is false");
if (a == b)
Console.WriteLine("a == b is true");
else
Console.WriteLine("a == b is false");
</code>
will generate the following output:

a.Equals(b) is false
a == b is true


Why?
 
...
Why is Int32.Equals(Int16) always false?

From the documentation for Int32.Equals:

"true if obj is an instance of Int32 and
equals the value of this instance;
otherwise, false."


Observe "if obj is an instance of Int32", as opposed to the == operator that
only compares by value.


// Bjorn A
 
John said:
Why is Int32.Equals(Int16) always false?
The following code:
<code>
Int32 a = 123;
Int16 b = 123;
if (a.Equals(b))
Console.WriteLine("a.Equals(b) is true");
else
Console.WriteLine("a.Equals(b) is false");
if (a == b)
Console.WriteLine("a == b is true");
else
Console.WriteLine("a == b is false");
</code>
will generate the following output:

a.Equals(b) is false
a == b is true

Why?

As the help file says, the return value is true if the passed object is
an instance of Int32 and equals the value of this instance; otherwise,
false. You are failing on the first check, your passed object is not an
instance of an Int32.
 
Back
Top