C # IF Simplification

5

I have this code, and I have been looking for a way to simplify it using a ternary operator, but I can not because it says I can not use decimal in string:

decimal per;
if (nud_qtPedida.Value != 0)
   per = nud_qtFornecida.Value * 100 / nud_qtPedida.Value;
else
  per = 0;
txt_percentagem.Text = per.ToString();
    
asked by anonymous 20.05.2016 / 11:28

1 answer

8

You can use a ternary operator to validate the nud_qtPedida.

  • You can start by doing this:

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

    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 ;

    
20.05.2016 / 11:36