As per this msdn documentation
If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method.
then why does following code results in two different result of method calls Equals
method returning True and ReferenceEquals
method returning false, even though the obj
and obj1
is reference type as IsClass
property returns true.
using System;
public class Program
{
public static void Main()
{
var obj = new { a = 1, b = 1 };
var obj1 = new { a = 1, b = 1 };
Console.WriteLine("obj.IsClass: " + obj.GetType().IsClass);
Console.WriteLine("object.ReferenceEquals(obj, obj1): " + object.ReferenceEquals(obj, obj1));
Console.WriteLine("obj.Equals(obj1): " + obj.Equals(obj1));
}
}
Output:
obj.IsClass: True
object.ReferenceEquals(obj, obj1): False
obj.Equals(obj1): True
To check for reference equality, use ReferenceEquals. To check for value equality, use Equals or Equals. By default, the operator == tests for reference equality by determining if two references indicate the same object, so reference types do not need to implement operator == in order to gain this functionality.
Difference between == and . Equals method in c# The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content.
ReferenceEquals() Method is used to determine whether the specified Object instances are the same instance or not. This method cannot be overridden.
Reference equality means that two object references refer to the same underlying object. This can occur through simple assignment, as shown in the following example. In this code, two objects are created, but after the assignment statement, both references refer to the same object.
obj
and obj1
refer to 2 different objects, so object.ReferenceEquals()
will return false.
Equals()
returns true, because the compiler implements Equals()
for anonymous types. It will return true if all the properties of both objects have the same values.
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