2

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 ?

Essex
  • 6,042
  • 11
  • 67
  • 139
  • Ok because Visuel Studio said that it's better to use ?: in my case – Essex May 29 '20 at 14:53
  • 5
    `worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo?.ToString() ?? string.Empty;` should work –  May 29 '20 at 14:53
  • Does this answer your question? [shorthand If Statements: C#](https://stackoverflow.com/questions/6073563/shorthand-if-statements-c-sharp) – Md. Suman Kabir May 29 '20 at 14:53

2 Answers2

5

You need to assign result of ternary operation

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

or you can use null coalescing operator ??,

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

Ternary Operator ?:

Syntax of ternary operator:

 output = condition ? expression 1 : expression 2;
  • If condition is true then result of expression 1 get assigned to output variable otherwise expression 2 will be assigned.

Null coalescing operator ?? (From MSDN)

operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

Null conditional operator ?.

If you notice in second solution, I used ?. operator, this operator is called as null conditional operator. This operator execute only if resultat.CodeAlgo is not-null. It will return null if resultat.CodeAlgo is null, this will help us to avoid null reference exception.

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
2

You assign the value to worksheet.Cells[ligne, 7].Value. so the code should be

worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo != null ? resultat.CodeAlgo.ToString() : string.Empty;
user2316116
  • 6,726
  • 1
  • 21
  • 35