ASP.NET Razor - C# Logic Conditions
Programming logic: executing code based on conditions.
If Condition
C# allows executing code based on conditions.
Use if statementto evaluate a condition. Based on the result, the if statement returns true or false:
- The if statement starts a code block
- The condition is written in parentheses
- If the condition is true, the code inside the braces is executed
Example
@{var price=50;}
@if (price>30)
{
The price is too high.
}Run Example »
Else Condition
An if statement can contain an else condition。
The else condition defines the code to be executed when the condition is false.
Example
@{var price=20;}
@if (price>30)
{
The price is too high.
} else {The price is OK.
}Run Example »
**Note:** In the example above, if the first condition is true, the code in the if block will be executed. The else condition covers "all other cases" except the if condition.
Else If Condition
Multiple condition checks can use an else if condition:
Example
@{var price=25;}
@if (price>=30)
{
The price is high.
} else if (price>20 && price<30) {The price is OK.
} else {The price is low.
}Run Example »
In the example above, 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 the else if conditions are true, the final else block (without a condition) covers "all other cases".
Switch Condition
A switch blockcan be used to test several individual conditions:
Example
@{
var weekday=DateTime.Now.DayOfWeek;
var day=weekday.ToString();
var message="";
}
@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;
}
@message
Run Example »
The test value (day) is written in parentheses. Each individual test condition has a case value ending with a semicolon and any number of code lines ending with a break statement. If the test value matches the case value, the corresponding code lines are executed.
A switch block has a default case (default:), which covers "all other cases" when none of the specified cases match.