Languages
[Edit]
EN

C# / .NET - compare strings

9 points
Created by:
Flimzy
596

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.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join