Search code examples
c#.netequalsequality

Why does integer.equals(string) give false when both contain the same value, but does not throw type mismatch exception?


I have code where I get a string as input, and I compare it with an integer.

I saw that integer variable also has an Equals function that accepts a string parameter.

I have used it directly thinking it will typecast it.

It did not give any compile time or runtime error, but it always gives a false result.

For example,

int sessionId = 1;

string requestId="1"

return sessionId.Equals(requestId);

sessionId.Equals(requestId) always gives false.

Why is the reason for such behavior? If there is a reason, why are they allowing it run without error?


Solution

  • Integers and strings are always different, and thus "1".Equals(1) returns false.

    It compiles because object.Equals(object other) takes an object as the right side, and thus accepts any type.