Tuur Tuur - 2 months ago 6
C# Question

How to check with an if statement, a text, but doesn't check the upper- and lowercases

So here is my code:

if (txtboxAntwoord.Text == lblProvincie.Text)
{

}


The thing I want to achieve is: make the
if statement
so that it does check if the text is the same, but it does not check if the text contains upper- or lowercases.

Let's say
lblProvincie's
text = "Some Text" and I want to check if the containing text of
txtboxAntwoord
is the same, but it shouldn't matter if it contains the uppercases of the text.

Answer

You can use the .Equals method on string and pass in a string comparison option that ignores case.

if (string.Equals(txtboxAntwoord.Text, lblProvincie.Text, 
               StringComparison.OrdinalIgnoreCase))

for pure speed where culture-based comparison is unimportant

OR

if (string.Equals(txtboxAntwoord.Text, lblProvincie.Text, 
               StringComparison.CurrentCultureIgnoreCase))

if you need to take culture-based comparisons into account.


While this approach may be slightly more complicated, it is more efficient than the ToUpper() approach since new strings do not need to be allocated. It also has the advantage of being able to specify different comparison options such as CurrentCultureIgnoreCase.

While this may not be much of an impact on application performance in an isolated context, this will certainly make a difference when doing large amounts of string comparisons.

const string test1 = "Test1";
const string test2 = "test1";

var s1 = new Stopwatch();
s1.Start();

for (int i = 0; i < 1000000; i++)
{
    if (!(test1.ToUpper() == test2.ToUpper()))
    {
        var x = "1";
    }
}
s1.Stop();
s1.ElapsedMilliseconds.Dump();

var s2 = new Stopwatch();
s2.Start();
for (int i = 0; i < 1000000; i++)
{
    if(!string.Equals(test1, test2,
           StringComparison.OrdinalIgnoreCase))
    {
        var x = "1";
    }
}
s2.Stop();
s2.ElapsedMilliseconds.Dump();

The first contrived example takes 265 milliseconds on my machine for 1 million iterations. The second only takes 25. In addition, there was additional string creation for each of those iterations.

Per Mike's suggestion in the comments, it is only fair to also profile CurrentCultureIgnoreCase. This is still more efficient than ToUpper, taking 114 milliseconds which is still over twice as fast as ToUpper and does not allocate additional strings.