How to use C #? for this expression

Why does he say that he cannot work with bool and int for

int sign = (op == "+" ?? 1 : -1); 

Should I use it if ... then instead, just do it?

0
source share
6 answers

Do you need to use the conditional operator ?: ::

 int sign = (op == "+" ? 1 : -1); 

Double question marks are the null-coalescing operator , which does a completely different thing.

+8
source

This syntax is not valid.

Conditional statement uses single ? .

+3
source

Because the correct syntax

 int sign = (op == "+" ? 1 : -1); 

with one question mark.

Two question mark syntax is used for the Null Coalescing Operator , while an expression requires a Conditional operator

+3
source

?? is a zero coalescing operator . op == "?" is an expression that returns a boolean value.

Are you looking for int sign = (op == "+" ? 1 : -1); that uses the conditional operator.

+2
source

You need only one question mark for the conditional operator (also known as the ternary operator).

 int sign = (op == "+" ? 1 : -1); 
+2
source

you should also check (depending on where the string comes from) check if you got an assignment with some string

  string op = "+"; int sign = ((op == "+") ? 1 : op.Length == 0? 0:-1); 

EDIT: fetch for null option

 int sign = (String.IsNullOrEmpty(op) ? 0 : (op == "+") ? 0 : -1); 
-1
source

Source: https://habr.com/ru/post/1485318/


All Articles