Alternative to If/Else

Asked

Viewed 530 times

2

I have the following code:

private void maskedTextBoxEAN_Leave(object sender, EventArgs e)
{
    if (!string.IsNullOrWhiteSpace(maskedTextBoxEAN.Text))
        if (!ValidaEAN13.CalculateChecksum(maskedTextBoxEAN.Text))
            CaixaMensagemDeErro.Mensagem("O código EAN digitado não é valido.");        
}

It works, but I wonder if there’s a better way to do this with less if/else, or even without.

Has as?

  • You can use the ternary operator ? and : but I don’t know if it’s a good option for nested ifs.

  • This is not if/Else, it is only if nested. and for this there is the && or || operation to check more than one condition.

1 answer

4


Without if/else should not be possible, but you can you can use the operator && to do in a if only:

private void maskedTextBoxEAN_Leave(object sender, CancelEventArgs e)
{
    if (!string.IsNullOrWhiteSpace(maskedTextBoxEAN.Text) &&
        !ValidaEAN13.CalculateChecksum(maskedTextBoxEAN.Text))
            CaixaMensagemDeErro.Mensagem("O código EAN digitado não é valido.");
}

Depending on how the method CalculateChecksum treats the argument, the IsNullOrWhiteSpace may not be necessary.

As a suggestion, you can use the ErrorProvider to inform the user of the error.

private void maskedTextBoxEAN_Leave(object sender, CancelEventArgs e)
{
    if (!ValidaEAN13.CalculateChecksum(maskedTextBoxEAN.Text){
        errorProvider1.SetError(maskedTextBoxEAN, "O código EAN digitado não é valido.");
        //e.Cancel = true;
    }
    else
    {
        errorProvider1.SetError(maskedTextBoxEAN, String.Empty);
        //e.Cancel = false;
    }
}

You can also cancel user action by setting as true to property Cancel of control.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.