C# IF simplification

Asked

Viewed 435 times

5

I have this code, and I’ve been searching for a way to simplify it using a ternary operator, but I’m not getting it because it says I can’t use decimal string:

decimal per;
if (nud_qtPedida.Value != 0)
   per = nud_qtFornecida.Value * 100 / nud_qtPedida.Value;
else
  per = 0;
txt_percentagem.Text = per.ToString();
  • 1

    Just be careful not to abuse the use of ternary operators, as they in some circumstances make it difficult to read and maintain the code. I see no problem in the question code that needs to be placed on a If ternary.

1 answer

8


You can use a ternary operator to validate nud_qtPedida.

  • You can start by doing like this:

    decimal per=nud_qtPedida.Value !=0 ? nud_qtFornecida.Value * 100 / nud_qtPedida.Value:0;
    txt_percentagem.Text = per.ToString();
    
  • Then you can do it all in one line if you understand:

    txt_percentagem.Text = (nud_qtPedida.Value !=0 ? nud_qtFornecida.Value * 100 / nud_qtPedida.Value:0).ToString();
    

Ternary Operator

The ternary operator works like this: Condição ? valor_se_verdadeiro : valor_se_falso;

  • I think the right thing would be something like Condição ? valor_se_verdadeiro : valor_se_falso. Affirmative and negative value is half meaningless.

  • You’re right, I’ll change it right away, thank you

Browser other questions tagged

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