EN
C# / .NET - compare strings
9 points
In this short article, we would like to show how to compare strings in C#.
Quick solution:
Use
Equals()
mehod for safety.
Practical example:
xxxxxxxxxx
1
String x = "Hello!";
2
String y = "Hello!";
3
4
if (object.Equals(x, y)) // or: x.Equals(y) when x != null
5
{
6
// Source code when strings are equal here ...
7
}
When we use ==
operator to compare strings, there is used ==
operator defined in String
class. To compare objects we should use Equals()
method.
So, the below source code, comparision returns true
value:
xxxxxxxxxx
1
String x = "Hello!";
2
String y = "Hello!";
3
4
if (x == y) // unsafe strings comparison !!!
5
{
6
// Source code when strings are equal here ...
7
}
But, for the changed source code, comparision returns false
value:
xxxxxxxxxx
1
// using System;
2
// using System.Text;
3
4
object x = new StringBuilder("Hello!").ToString();
5
object y = new StringBuilder("Hello!").ToString();
6
7
Console.WriteLine(x == y); // False
It is caused by: how x
and y
variables are stored and what type have.