Evaluating else if after if condition

Consider this snippet:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }                
}

Why does this not evaluate the second condition (less than the condition)? This is also true, isn't it?

If I need to get the second to work in the same state, what minor changes should be made?

+3
source share
10 answers

else if checked only if the first condition is not met.

If you want both of them to be true, you must do

if(textBox1.MaxLength > 0 && textBox1.MaxLength < 32768)
{
   // do stuff here
}
+6
source

, else , false. , . if, :

if (textBox1.MaxLength > 0 && textBox1.MaxLength < 32768)
{
    textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
}
+8

, if , ? else

+2

else, , .

+1

, . , :

 if (textBox1.MaxLength > 0 && textBox1.MaxLength < 32768)

&& :

if (A && B) {
    //do something
} 

if (A) { 
    if (B) { 
        //do something 
    } 
}
+1

, , , if-then, "else". firt, ( ).

+1

if, 0 if , . , if n, n > 0, if 32768 > n > 0.

+1

, "else if" , ,

if (textBox1.MaxLength > 0) 

, MaxLength, , 0, 0.

,

textBox1.MaxLength < 32768

, .

0, , .

+1
source

Think about else ifhow it is actually written like this:

private void button1_Click(object sender, EventArgs e)
{
    //textBox2.Text += Convert.ToString (textBox1.Text + "garment");
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else
    {
        if (textBox1.MaxLength < 32768)
        {
            textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
        }
    }
}

It is the same. Note that the second ifsstatement is only executed when the first is false.

+1
source

I would do this if I wanted to say "if MaxLength is between 0 and 32768":

if (0 < textBox1.MaxLength && textBox1.MaxLength < 32768)
    textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();

Since you are doing the same in this interval, it is more advisable to do both in the same condition.

+1
source

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


All Articles