Difference between Equals() and == in C# String

Equals() method and == sign are equality operators. The difference is that Equals() method is used to compare two strings that too only content where as == is used to compare two objects of any data type and compares the reference identity.

Lets see few examples:

String val1 = "Hello";
String val2 = "Hi";
Console.WriteLine("s1 = {0}", val1);
Console.WriteLine("s2 = {0}", val2);
Console.WriteLine();
Console.WriteLine("s1 == s2: {0}", val1 == val2);
Console.WriteLine("s1 == Hello: {0}", val1 == "Hello");
Console.WriteLine("s1 == HELLO: {0}", val1 == "HELLO");
Console.WriteLine("s1 == hello: {0}", val1 == "hello");
Console.WriteLine("s1.Equals(s2): {0}", val1.Equals(val2));
Console.WriteLine("Hi.Equals(s2): {0}", "Hi".Equals(val2));

Below is the result of the above code:

String name = "David";
char[] arrName = {'D','a','v','i','d'};
object myName = new String(arrName); 
Console.WriteLine("Result using == operator: {0}", myName == name);
Console.WriteLine("Result uisng Equals() method: {0}", myName.Equals(name));

Below is the result of above code:

null.Equals(value); returns the NulReferenceExceltion whereas value.Equals(null); returns the bool value. == operator can have null value on either side of the operator.
Below is a sample code: 

String name = "David";
String name1 = null;
Console.WriteLine("Result using == operator: {0}", name == name1);
Console.WriteLine("Result uisng Equals() method: {0}", name1.Equals(name));

Below is the result of the above code:

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started