C# Decision Making

A decision structure requires the programmer to specify one or more conditions to be evaluated or tested, along with statements to be executed if the condition is true (required) and statements to be executed if the condition is false (optional).

The following is the general form of a typical decision structure in most programming languages:

C# 中的判断语句

Decision Statements

C# provides the following types of decision statements. Click the links to see the details of each statement.

statementDescription
if statementaif statementConsists of a Boolean expression followed by one or more statements.
if...else statementaif statementCan be followed by an optionalelse statementThe else statement is executed when the Boolean expression is false.
Nested if StatementsYou can in aiforelse ifUse another within a statementiforelse ifstatement.
switch statementaswitchThe statement allows testing a variable for equality against multiple values.
Nested switch StatementsYou can in aswitchUse another within a statementswitch statement.
C# Null Conditional OperatorC# 6.0 introduced the Null-conditional operator?.used to safely access properties or methods without having to write a bunch of if checks.

? : operator

We have already explained in the previous chaptersConditional Operator ? :, can be used to replaceif...elseStatement. Its general form is as follows:

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Note the use and placement of the colon.

The value of the ? expression is determined by Exp1. If Exp1 is true, then Exp2 is evaluated, and its value becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated, and its value becomes the value of the entire ? expression.

other extensions