Internally, == is implemented as the operator overloading method, so the result depends on how that method is overloaded.
In the same way,
Object.Equals() method is a virtual method and the result depends on the implementation.
For example, the == operator and
.Equals() compare the values of the two built-in value types variables. if both values are equal then returns
true; otherwise returns
int i = 10, j = 10; Console.WriteLine(i == j); // true Console.WriteLine(i.Equals(j)); // true
For the reference type variables, == and
.Equals() method by default checks whether two two object instances are equal or not.
However, for the string type, == and
.Equals() method are implemented to compare values instead of the instances.
string str1 = "Hello", str2 = "Hello", str3 = "hello"; Console.WriteLine(str1 == str2); // true Console.WriteLine(str1 == str3 ); // false Console.WriteLine(str1.Equals(str2));// true Console.WriteLine(str1.Equals(str3));// false
Now, look at the following example:
object obj1 = "Hello"; object obj2 = "Hello"; Console.WriteLine(obj1 == obj2); // true Console.WriteLine(obj1.Equals(obj2)); // true
In the above example, it looks like == and
Equals() method compares values. However, they compare instances. C# points two objects to the same memory address if both the values are equal. So, they return
Now, check the following:
object obj1 = new StringBuilder("Hello"); object obj2 = "Hello"; Console.WriteLine(obj1 == obj2); // false Console.WriteLine(obj1.Equals(obj2));// false
In the above example,
obj1 points to StringBuilder type object and
obj2 is string type, so both are different instances even if they have same values.
So, == and
Equals() method compares the instances and return
false because they are different instances.
- Asynchronous programming with async, await, Task in C#
- How to loop through an enum in C#?
- Generate Random Numbers in C#
- Difference between Two Dates in C#
- Convert int to enum in C#
- BigInteger Data Type in C#
- Convert String to Enum in C#
- Convert an Object to JSON in C#
- Convert JSON String to Object in C#
- DateTime Formats in C#
- How to convert date object to string in C#?
- Compare strings in C#
- How to count elements in C# array?
- Difference between String and string in C#.
- How to get a comma separated string from an array in C#?
- Boxing and Unboxing in C#
- How to convert string to int in C#?