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

3

I have a little doubt with the following code:

int n1 = 20;

int n2 = 10;

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

Console.WriteLine(n3);
Console.ReadKey();

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
source

2 answers

8

It's a short IF,

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

This translates as:

int n3;
if(n1>n2){
 n3 = n1;
}else{
 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
0

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