What is the operator for? : (conditional operator) in C #


I have a little doubt with the following code:

int n1 = 20;

int n2 = 10;

int n3 = (n1 > n2) ? n1:0;


I do not understand why n3 ends up being 20 What roles fulfill the ? and the n1:0 in that case?

asked by novatito 18.05.2017 в 02:03

2 answers


It's a short IF,

int n3 = (n1 > n2) ? n1:0;

This translates as:

int n3;
 n3 = n1;
 n3 = 0;

I recommend that you use the "if short" when you have a simple structure like the present example.

answered by 18.05.2017 в 02:14

This happens since this type of operation makes a check before assigning a value to the variable.

var value = (condition)? true: false;

true: assign the value if the condition is true.

false: assign the value if the condition is false.

In case you have any doubts I leave you a documentation .

answered by 22.05.2017 в 18:47