C# String.Equality (==) Operator with Example

In this tutorial, we will learn about the String.Equality (==) operator with its usage, syntax, and examples. By IncludeHelp Last updated : April 07, 2023

C# String.Equality (==) Operator

The String.Equality (==) operator is used to check whether two strings objects have the same values or not.

Syntax

public static bool operator == (string a, string b);

Parameter(s)

  • string a: The first string to be compared.
  • string b: The second string to be compared.

Return Value

bool – it returns a Boolean value. If strings have the same value, it returns true, else it returns false.

Example

Input:
string str1 = "IncludeHelp";
string str2 = "IncludeHelp";

String.Equality:
str1 == str2;

Output:
true

C# example to compare two strings using String.Equality (==) operator

using System;
using System.Text;

namespace Test {
  class Program {
    static void Main(string[] args) {
      string str1 = "IncludeHelp";
      string str2 = "IncludeHelp";

      //comparing strings
      Console.WriteLine("str1==str2: " + (str1 == str2));
      if (str1 == str2)
        Console.WriteLine("str1 and str2 have the same values");
      else
        Console.WriteLine("str1 and str2 don't have the same values");

      str1 = "Hello world";
      str2 = "IncludeHelp";

      //comparing strings
      Console.WriteLine("str1==str2: " + (str1 == str2));
      if (str1 == str2)
        Console.WriteLine("str1 and str2 have the same values");
      else
        Console.WriteLine("str1 and str2 don't have the same values");

      //hit ENTER to exit
      Console.ReadLine();
    }
  }
}

Output

str1==str2: True
str1 and str2 have the same values
str1==str2: False
str1 and str2 don't have the same values

Reference: String.Equality(String, String) Operator




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.