Can someone interpret this line of code?

int salesTeamId = person == null ? -1 : person.SalesTeam.Id; 

From what I can put together:

  • int SalesTeamId is a variable, and a variable is assigned to the person.

After that I got lost. Any directions?

+6
source share
7 answers

This is a threefold statement. I translated it into an if / else block for reading.

 int salesTeamId; if(person == null) { salesTeamId = -1; } else { salesTeamId = person.SalesTeam.Id; } 
+12
source

This is the Ternary operator . This is a shorthand if equivalent to:

 int salesTeamId; if( person == null ) { salesTeamId = -1; } else { salesTeamId = person.SalesTeam.Id; } 
+8
source

It means,

 int salesTeamId; if (person == null) salesTeamId = -1; else salesTeamId = person.SalesTeam.Id; 
+4
source

It is called a conditional statement.

The conditional operator (? :) is the ternary operator (it takes three operands). The conditional statement works as follows:

  • The first operand is implicitly converted to bool. It is evaluated and all side effects are completed before proceeding.
  • If the first operand evaluates to true (1), the second operand is evaluated.
  • If the first operand evaluates to false (0), the third operand is evaluated.

An example is roughly equivalent to this code:

 int salesTeamId; if (person == null) { salesTeamId = -1; } else { salesTeamId = person.SalesTeam.Id; } 
+3
source

Its implicit if statement (called the ternary operator).

Basically checking it, if the person is null, returns -1 else return person.SalesTeam.id. The return value is then assigned directly to the salesTeamId variable.

 int salesTeamId; if(person == null) { salesTeamId = -1; } else { salesTeamId = person.SalesTeam.Id } 

is the direct equivalent

+2
source

It is equivalent

 int salesTeamId; if (person == null) salesTeamId = -1; else salesTeamId = person.SalesTeam.Id; 

Note ?: Operator (C #)

+2
source

If the person is null, then salesTeamId is set to -1. If the person is null null, then salesTeamId is assigned to person.SalesTeam.Id.

The tertiary operator is an if-then-else statement embedded in one line (this can usually be scattered across multiple lines, but this is somewhat surprising).

This may be clear to add parentheses:

 int salesTeamId = (person == null ? -1 : person.SalesTeam.Id); 

The following pseudo code may also help:

 int salesTeamId = (IF person == null THEN USE -1 ELSE USE person.SalesTeam.Id ); 
+1
source

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


All Articles