C# String Equals()

The String Equals() method checks whether two strings have the same value or not.

Example

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str1 = "Ice cream";
      string str2 = "Ice cream";

// comparing str1 with str2 bool result = String.Equals(str1, str2);
Console.WriteLine(result); Console.ReadLine(); } } } // Output: True

Equals() Syntax

The syntax of the string Equals() method is:

String.Equals(string a, string b)

Here, Equals() is a method of class String.


Equals() Parameters

The Equals() method takes the following parameters:

  • a - first string to compare
  • b - second string to compare

Equals() Return Value

The Equals() method returns:

  • True - if the strings are equal
  • False - if the strings are not equal

Example 1: C# String Equals()

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str1 = "Ice cream";
      string str2 = "Ice cream";
      string str3 = "Chocolate";

      bool result;

// comparing str1 with str2 result = String.Equals(str1, str2);
Console.WriteLine("str1 and str2 are equal: " + result);
// comparing str1 with str3 result = String.Equals(str1, str3);
Console.WriteLine("str1 and str3 are equal: " + result); Console.ReadLine(); } } }

Output

str1 and str2 are equal: True
str1 and str3 are equal: False

Here,

  • String.Equals(str1, str2) - returns True as str1 and str2 are equal
  • String.Equals(str1, str3) - returns False as str1 and str3 are not equal

Example 2: Check if Two Strings Are Equal

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str1 = "Ice cream";
      string str2 = "Ice cream";
      
// compares str1 and str2 if(String.Equals(str1, str2))
{ Console.WriteLine("str1 and str2 are equal"); } else { Console.WriteLine("str1 and str2 are not equal"); } Console.ReadLine(); } } }

Output

str1 and str2 are equal

Example 3: Equals() With Case

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str1 = "Ice cream";
      string str2 = "ice cream";
      
// compares str1 and str2 bool result = String.Equals(str1, str2);
Console.WriteLine("str1 and str2 are equal: " + result); Console.ReadLine(); } } }

Output

str1 and str2 are equal: False

When "Ice cream" is compared to "ice cream", we get False. This is because Equals() considers the letter case.

Note: We can use the StringComparison parameter to ignore or consider letter cases while comparing strings. For example,

String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase)
Did you find this article helpful?