Programming Logic: Executes code based on conditions.
If condition
C # allows code execution based on conditions.
Use the if statement to determine the condition. The IF statement returns TRUE or false based on the result of the decision:
- 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
Instance@{var price=50;}
<body>
@if (PRICE>30)
{
<p>the Price is too high.</p>
}
</body>
Running Instances»
Else condition
An If statement can contain an else condition .
The else condition defines the code that is executed when the condition is false.
Instance@{var price=20;}
<body>
@if (PRICE>30)
{
<p>the Price is too high.</p>
}
Else
{
<p>the Price is ok.</p>
}
</body>
Running Instances»
Note: in the above example, if the first condition is true, the code for the If block will be executed. The else condition overrides "all other cases" except for the IF condition.
Else If Condition
Multiple criteria can be judged using the else if condition :
Instance@{var price=25;}
<body>
@if (price>=30)
{
<p>the Price is high.</p>
}
else if (price>20 && price<30)
{
<p>the Price is ok.</p>
}
Else
{
<p>the Price is low.</p>
}
</body>
Running Instances»
In the above example, if the first condition is true, the code for the If block will be executed.
If the first condition is not true and the second condition is true, the code for the else if block will be executed.
The number of else if conditions is not restricted.
If the IF and else if conditions are not true, the last else block (without conditions) overrides "all other cases."
Switch condition
A switch block can be used to test a few separate conditions:
Instance@{
var Weekday=datetime.now.dayofweek;
var day=weekday. ToString ();
var message= "";
}
<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>
Running Instances»
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:), and when all the specified conditions do not match, it overrides "all other cases".
ASP. NET razor-c# Logic conditions