It is because operators can't be virtual
, because of that you are calling the ==
operator on Object
.
The ==
operator for object compares references. For structs (like int
) when cast to a object
it will "box" the struct in to a class reference. The code
object int1 = 1;
object int2 = 1;
causes two boxes to be made so when you call ==
on the box it sees the other side is not the same box so it returns false.
Strings are already reference types so they don't get a extra box made when they are put in to a object
. However the compiler treats them special, in the following code
object str1 = "shahrooz";
object str2 = "shahrooz";
The compiler only makes one shahrooz
string in memory and assigns it to both str1
and str2
. This is why it returns true
when you compare them.
If you did the code
public static void Main()
{
object str1 = "shahrooz";
object str2 = "shah" + Console.ReadLine();
Console.WriteLine(str1 == str2);
Console.ReadLine();
}
and typed in rooz
you would get false
as your result because you now have two different string references even though they have the same string content.
use the method Equals
instead of ==
, that does check if the Equals
method was overloaded on derived classes and will unbox structs to compare them.