Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

evaluating else if after an if condition is true

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 is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?

like image 222
Marie Curie Avatar asked Nov 29 '22 18:11

Marie Curie


2 Answers

The second condition isn't being checked because an else statement will only be evaluated when the preceding conditions are evaluated to be false. There are several ways to fix this, some of which are shown in other answers. One such way is to use a single if statement, which combines both conditions:

if (textBox1.MaxLength > 0 && textBox1.MaxLength < 32768)
{
    textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
}
like image 54
Donut Avatar answered Dec 10 '22 14:12

Donut


else if is only checked if the first condition isn't satisfied.

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

if(textBox1.MaxLength > 0 && textBox1.MaxLength < 32768)
{
   // do stuff here
}
like image 42
Adam Lear Avatar answered Dec 10 '22 13:12

Adam Lear