C# Program to Check Given Strings are Equal or Not Using equal to (==) Operator
Last Updated :
11 Nov, 2021
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#
using System;
class GFG{
public static void Main()
{
string str1 = "geeks" ;
string str2 = "geeks" ;
Console.WriteLine(str1 == str2);
}
}
|
Example 2:
C#
using System;
class GFG{
public static void Main()
{
string str1 = "geeks" ;
string str2 = "geeqs" ;
Console.WriteLine(str1 == str2);
}
}
|
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#
using System;
class GFG{
static void Main( string [] args)
{
object str1 = "geeks" ;
object str2 = new string ( "geeks" );
Console.WriteLine(str1 == str2);
}
}
|
Share your thoughts in the comments
Please Login to comment...