C # If Equals Case is insensitive

The following code will open a message box containing the word "Fail".

Is there a way to make the if case insensitive, so that the if statement goes through and opens the mbox in contact with "Pass" without converting the character / string to upper / lower case?

here is the code:

public partial class Form1 : Form
    {
        string one = "A";
        string two = "a";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (one == two)
            {
                MessageBox.Show("Pass");
            }
            else
            {
                MessageBox.Show("Fail");
            }
        }
    }

Thank you in advance

+4
source share
7 answers

You can use this

string.Equals(one, two, StringComparison.CurrentCultureIgnoreCase)

Your code will be

if (string.Equals(one, two, StringComparison.CurrentCultureIgnoreCase))
{
   MessageBox.Show("Pass");
}
else
{
   MessageBox.Show("Fail");
}


Using CurrentCultureIgnoreCase :

Compare strings using culture-based sorting rules, the current culture, and ignoring the case of string comparisons

More here

+9
if (string.Equals(one, two, StringComparison.CurrentCultureIgnoreCase))

MSDN:

StringComparer.CurrentCultureIgnoreCase

StringComparer, , .

+3

:

if (String.Compare(one, two, StringComparison.CurrentCultureIgnoreCase) == 0) {
   // they are equal
}

2:

if ((one ?? "").ToLower() == (two ?? "").ToLower())
   // they are equal
}

, !

. , , - . , . , , .

+1

:

if(StringComparer.OrdinalIgnoreCase.Equals(one, two)) 

, .

0

.Equals() . StringComparison.OrdinalIgnoreCase , .

0

string one = "obi";
 string two = "Obi";

 if(one.Equals(two, StringComparison.OrdinalIgnoreCase))
{
   /* Your code */
}
0
if(one.ToLower() == two.ToLower())
{
    //Do stuff
}
-2

Source: https://habr.com/ru/post/1527588/


All Articles