Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do the results of the Equals and ReferenceEquals methods differ even though variables are reference types?

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

like image 602
Jenish Rabadiya Avatar asked Nov 23 '15 11:11

Jenish Rabadiya


People also ask

What is the most accurate way to check for equality by reference?

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.

What is the difference between Equals () and == in C#?

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.

What does reference equal mean?

ReferenceEquals() Method is used to determine whether the specified Object instances are the same instance or not. This method cannot be overridden.

What is reference equality in C#?

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.


1 Answers

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.

like image 154
Dennis_E Avatar answered Oct 05 '22 23:10

Dennis_E