Alternative for If / Else

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 is a better way to do this with less if/else , or even without.

What is it like?

    
asked by anonymous 13.08.2016 / 03:18

1 answer

4

No if/else should not be possible, but you can use the && 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 CalculateChecksum method handles the argument, IsNullOrWhiteSpace may not be necessary.

As a suggestion, you can use 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 the user action by setting true to property Cancel of the control.

    
13.08.2016 / 03:37