vendredi 29 mai 2020

Convert if/else statement to ?: operator C#

I would like to reduce my code to something better. That's why I'm trying to convert if/else statement to operator ?:

My actual code looks like this :

if (resultat.CodeAlgo != null)
 {
    worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo.ToString();
 }
else
 {
    worksheet.Cells[ligne, 7].Value = string.Empty;
}

I tried to convert to :

resultat.CodeAlgo != null
  ? worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo.ToString()
  : worksheet.Cells[ligne, 7].Value = string.Empty;

But it said :

Only assignment, call, increment, decrement, and new object statement can be used as a statement.

First time I'm using this operator and I don't understand why my simplification is wrong ?

Aucun commentaire:

Enregistrer un commentaire