C# Program to Check Given Strings are Equal or Not Using equal to (==) Operator
Given two strings we need to check if they are equal by using the == operator. The == Operator compares the reference identity i.e. whether they are referring to the same identity in the heap. If they are equal then it will return true, otherwise, return false.
Example:
Input String 1 : geeks String 2 : geeks Output : Equal Input String 1 : geeks String 2 : geeqs Output : Not Equal
Method:
For the given two strings compare them by using == operator
- If it returns true then the strings are equal.
- If it returns false then the strings are not equal.
Example 1:
C#
// C# program to check given strings are // equal or not. Using == operator using System; class GFG{ public static void Main() { string str1 = "geeks" ; string str2 = "geeks" ; // Here we use == operator to check // the equality of the strings Console.WriteLine(str1 == str2); } } |
Output
True
Example 2:
C#
// C# program to check given strings // are equal or not. Using == operator using System; class GFG{ public static void Main() { string str1 = "geeks" ; string str2 = "geeqs" ; // Here we use == operator to check // the equality of the strings Console.WriteLine(str1 == str2); } } |
Output
False
But the == operator might not work as expected when we are comparing strings whose reference identities are not the same. Let us understand with the help of the below example:
C#
// C# program to check given strings // are equal or not. Using == operator using System; class GFG{ static void Main( string [] args) { object str1 = "geeks" ; object str2 = new string ( "geeks" ); Console.WriteLine(str1 == str2); } } |
Output
False
Please Login to comment...