In C# object, When I compare 2 string's (same value) with equality operator I getting result as "True" but whereas if I compare 2 Integer's (same value) with equality operator I'm getting "False".
Can anyone explain me how this thing works?
using ConsoleApp1;
object obj1 = "Hello";
object obj2 = "Hello";
object obj3 = 5;
object obj4 = 5;
Console.WriteLine(obj1 == obj2); // True
Console.WriteLine(obj1.Equals(obj2)); // True
Console.WriteLine(obj3 == obj4); // False // This should be true right?
Console.WriteLine(obj3.Equals(obj4)); // True
There are several things which come in play:
Equals and == operatorstring instance for all compile time constants with the same value).object obj1 = "Hello";
object obj2 = "Hello";
object obj2_2 = "Hell" + getO(); // "Hello", but different instance
object obj3 = 5; // boxed to one instance with value 5
object obj4 = 5; // boxed to another instance with value 5
Console.WriteLine(obj1 == obj2); // True
Console.WriteLine(obj1.Equals(obj2)); // True
Console.WriteLine(obj1 == obj2_2); // False
Console.WriteLine(obj1.Equals(obj2_2)); // True
Console.WriteLine(obj3 == obj4); // False
Console.WriteLine(obj3.Equals(obj4)); // True
string getO() => "o";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With