ASP.NET Basics (part 3): Hard Choices - Do It Or Else... (Page 3 of 8 )
In addition to the "if" statement, C# also offers the "if-else" statement, which allows you to execute different blocks of code depending on whether the expression is evaluated as true or false.
The structure of an "if-else" statement looks like this:
if (condition)
{
do this!
}
else
{
do this!
}
In this case, if the conditional expression evaluates as false, all statements within the curly braces of the "else" block will be executed.
Modifying the example above, we have
<script language="c#" runat="server">
void Page_Load()
{
// temperature
int temp = 25;
if (temp > 35)
{
message.Text = "Man, it's hot out there!";
}
else
{
message.Text = "Well, at least it isn't as hot as it could be!";
}
}
</script>
<html>
<head><title>Weather Forecast</title></head>
<body>
<asp:label id="message" runat="server" />
</body>
</html>
In this case, if the first past of the construct fails (temperature is
*not* greater than 35), control is transferred to the second part - the "else" statement - and the code within the "else" block is executed instead. You can test both possibilities by adjusting the value of the "temp" variable, and viewing the resulting output in your browser.
Here's the output:


Next: Cookie-Cutter Code >>
More ASP.NET Code Articles
More By Harish Kamath (c) Melonfire