TranQ TranQ - 1 month ago 8
C# Question

Why short(-1) not equal to -1 in c#

In MVC4,.net 4.6.1 and VS 2015, I write a simple MVC app to pass a short type value from view to controller like this

public bool GetTheValue (short req_division)
{ return req_division == -1 ;}


The weird thing is when I pass -1 to val from my view, the result returned false. I don't know why is it happened. Can anyone explain it for me.
Thank you very much !

enter image description here

Answer

Besides the possible typo in your code, I found something strange in the evaluation that the Debug View does. See this code:

The debugger says it is false, yet the code evaluates to true. Maybe you have hit a type conversion issue in the debugger. When changing the int to a short, the debugger thinks i == j evaluates to true after all.