Monday, 29 April 2024

Equality Operator (==) and Equals() Method

 

 Difference between the Equality Operator (==) and Equals() Method in C#?

Although both are used to compare two objects by value, still they both are used differently. 

For ex.:

int x = 10;
int y = 10;
Console.WriteLine( x == y);
Console.WriteLine(x.Equals(y));
Output:
True
True

Equality operator (==) is a reference type which means that if equality operator is used, it will return true only if both the references point to the same object.  

Equals() method: Equals method is used to compare the values carried by the objects. int x=10, int y=10. If x==y is compared then, the values carried by x and y are compared which is equal and therefore they return true. 

Equality operator: Compares by reference

Equals(): Compares by value

No comments:

Post a Comment

Car pooling app

 I'll create a car pooling app with real-time vehicle tracking, pickup/drop time estimates, and a list of onboard users. Since we don...