ASP.NET Basics (part 3): Hard Choices - Three In One (Page 5 of 8 )
So far, I have demonstrated various mathematical and logical operators. There is one thing common to all these operators - they all require at least two operands (the variables and constants that operators work with). For example, in the following code snippet
<%
c = a + b;
%>
the + operator requires two operands, the variables "a" and "b". Similarly, I have also used two operands with the = operator; the variable "c" and the expression "a + b". All such operators are commonly referred to as "binary" operators.
There are also some operators that require only one operand. Can you think of any? If the auto-increment (++) or auto-decrement (--) operators demonstrated last time came to mind, give yourself a little pat on the back.
<%
a++;
%>
For the record, these operators are also known as "unary" operators.
What does all this have to do with anything? Patience, I'm getting to the point. You might remember how, a few pages ago, I demonstrated the "if-else" conditional statement. C# offers a convenient alternative - the ? conditional operator. The syntax for this operator is as below:
conditional expression
? run this when true : run this when false
Perplexed? It's actually petty simple. When the compiler encounters a statement like the one above, it will evaluate the conditional expression and execute the first statement if the expression evaluates as true, and the second one if false. So the line of code above could also be expanded into the following equivalent:
if (conditional expression)
{
run this when true
}
else
{
run this when false
}
In order to better understand the shortcut syntax demonstrated above, here's a rewrite of a previous example using this syntax:
<script language="C#" runat="server">
void Page_Load()
{
int temp = 45;
message.Text = (temp > 35) ? "Man, it's hot out there!" : "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>
This operator is also an example of the so-called "ternary" operators, which requires three operands (in this case, the conditional expression and two alternatives).
The primary advantage of using this conditional operator is that the code becomes extremely compact (and, once you're used to it, very easy to read). This is evident from the code listings of the two examples above - the one using the ternary operator is shorter and more concise than the one using the traditional "if-else" syntax.
Next: Friday The 13th >>
More ASP.NET Code Articles
More By Harish Kamath (c) Melonfire