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:
String x = "Hello!";
String y = "Hello!";
if (object.Equals(x, y)) // or: x.Equals(y) when x != null
{
// Source code when strings are equal here ...
}
Trouble shooting
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:
String x = "Hello!";
String y = "Hello!";
if (x == y) // unsafe strings comparison !!!
{
// Source code when strings are equal here ...
}
But, for the changed source code, comparision returns false value:
// using System;
// using System.Text;
object x = new StringBuilder("Hello!").ToString();
object y = new StringBuilder("Hello!").ToString();
Console.WriteLine(x == y); // False
It is caused by: how x and y variables are stored and what type have.