Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equality operator for Integer Object and String Object working differently

Tags:

c#

.net

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
like image 219
Gowtham Raj Avatar asked Jun 26 '26 06:06

Gowtham Raj


1 Answers

There are several things which come in play:

  1. Difference between Equals and == operator
  2. String interning (compiler uses the same string instance for all compile time constants with the same value).
  3. Boxing of value types (see also value types and reference types article)
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";
like image 186
Guru Stron Avatar answered Jun 27 '26 22:06

Guru Stron