Programming logic: Execute code based on conditions.
C# allows conditional execution of code.
Use if statements to determine conditions. Depending on the judgment result, the if statement returns true or false:
if statement starts a block of code
Conditions are written in parentheses
If the condition is true, the code inside the curly braces is executed
@{var price=50;} <html> <body> @if (price>30){<p>The price is too high.</p>} </body> </html>
If statements can contain else conditions .
The else condition defines the code to be executed when the condition is false.
@{var price=20;} <html> <body> @if (price>30){<p>The price is too high.</p>}else{<p>The price is OK.</p>} </body> </html>
Note: In the above example, if the first condition is true, the code in the if block will be executed. The else condition covers "everything else" except the if condition.
Multiple conditional judgments can use else if conditions :
@{var price=25;} <html> <body> @if (price>=30){<p>The price is high.</p>}else if (price>20 && price<30) {<p>The price is OK.</p> p>}else{<p>The price is low.</p>} </body> </html>
In the above example, if the first condition is true, the code in the if block will be executed.
If the first condition is not true and the second condition is true, the code in the else if block will be executed.
There is no limit to the number of else if conditions.
If neither the if nor else if conditions are true, the final else block (without the condition) covers "everything else".
A switch block can be used to test some individual conditions:
@{var weekday=DateTime.Now.DayOfWeek;var day=weekday.ToString();var message="";} <html> <body> @switch(day){case "Monday":message="This is the first weekday.";break;case "Thursday":message="Only one day before weekend.";break;case " Friday":message="Tomorrow is weekend!";break;default:message="Today is " + day;break;} <p> @message </p> </body> </html>
The test value (day) is written in parentheses. Each individual test condition has a case value ending with a semicolon and any number of lines of code ending with a break statement. If the test value matches the case value, the corresponding line of code is executed.
The switch block has a default case (default:), which overrides "all other cases" when none of the specified cases match.