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

Category: C SharpDifference between the Equality Operator (==) and Equals() Method in C#?
Editor">Editor Staff asked 2 years ago

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

1 Answers
Editor">Editor Staff answered 2 years ago

Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items. The Equality Operator (==) is the comparison operator and the Equals() method compares the contents of a string. The == Operator compares the reference identity while the Equals() method compares only contents. Let’s see with some examples.

 
In this example, we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.

 

  1. using System;    
  2. namespace ComparisionExample {    
  3.     class Program {    
  4.         static void Main(string[] args) {    
  5.             string name = “sandeep”;    
  6.             string myName = name;    
  7.             Console.WriteLine(“== operator result is {0}”, name == myName);    
  8.             Console.WriteLine(“Equals method result is {0}”, name.Equals(myName));    
  9.             Console.ReadKey();    
  10.         }    
  11.     }    
  12. }