Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is == operator defined in Class "object"?

Tags:

c#

.net

I searched the source code of FCL, and I got confused that string.Equals() uses Object.ReferenceEquals(), and Object.ReferenceEquals() uses == operator to jugde. And then I can't find how the == operator is defined.

So where is the original operator defined?

like image 663
喵喵喵 Avatar asked Dec 09 '15 07:12

喵喵喵


People also ask

What is the difference between equals () and == 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.

How do you compare objects in C#?

The most common way to compare objects in C# is to use the == operator. For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object.

Is an example of an equality operator in C#?

The == (equality) and != (inequality) operators check if their operands are equal or not.

Should I override equality and inequality operators?

In a class, if you overload the Equals method, you should overload the == and != operators, but it is not required.


1 Answers

This is an operator that the language uses to validate that two values are the same. When your code would be compiled this operator would be compiled appropriately in CIL and then when we will be executed by the CLR the two values would be compared to be checked if they are the same.

For instance, this is the CIL code for the Main method:

Enter image description here

that the compiler produces for the following program (it's a console application):

class Program {     static void Main(string[] args)     {         int a = 3;         int b = 4;         bool areEqual = a == b;         Console.WriteLine(areEqual);     } } 

Note the IL_0007 line. There a ceq instruction has been emitted. This is that you are looking for, the == operator.

Important Note

This is happening when the == is not overloaded.

like image 130
Christos Avatar answered Oct 02 '22 11:10

Christos