3

Consider this code:

static int x2 = 10;

public static void Main()
{
     short y = 10;
     Console.WriteLine(y.Equals(x2)); //False
     Console.Read();
}

Why y.Equals(x2) returns false?

Wesley Lomax
  • 1,979
  • 2
  • 17
  • 34
  • 2
    From doc; _If an implicit conversion between the obj argument and an `Int16` is defined and the argument is not typed as an `Object`, compilers perform an implicit conversion and call the `Equals(Int16)` method. Otherwise, they call the `Equals(Object)` method, which always returns `false` if its obj argument is not an `Int16` value._ – Soner Gönül Oct 27 '15 at 08:16
  • No this is not my question –  Oct 27 '15 at 08:18
  • 1
    An int is not a short: please look at this: http://blog.coverity.com/2014/01/13/inconsistent-equality/ – Juergen Gutsch Oct 27 '15 at 08:19

2 Answers2

9

Int16.Equals specific docs

Return Value

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


This was my original answer, whilst it doesn't apply here, I've left it in as a note for what the .Equals method is checking for

From the docs,

the Equals(Object) method tests for reference equality

Community
  • 1
  • 1
Sayse
  • 38,955
  • 14
  • 69
  • 129
4

From the documentation, you can read that the specific overload used:

Returns a value indicating whether this instance is equal to a specified object.

And:

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

A short is not an int, so it returns false.

Patrick Hofman
  • 143,714
  • 19
  • 222
  • 294