ASP.NET Basics (part 3): Hard Choices - Apples And Oranges (Page 2 of 8 )
You'll remember how, in the second part of this tutorial, I used a bunch of mathematical operators to demonstrate how you could perform mathematical operations with numeric variables. But C# doesn't just stop at numeric and string operators - the language also comes with a bunch of comparison operators, whose sole raison d'etre is to evaluate expressions and determine if they are true or false.
The following table should make this clearer.
assume x=4 and y=10
Operator What It Means Expression Result
----------------------------------------------------------------
== is equal to x == y False
!= is not equal to x != y True
> is greater than x > y False
< is less than x < y True
>= is greater than
or equal to x >= y False
<= is less than
or equal to x <= y True
Why do you need to know all this? Well, comparison operators come in very useful when building conditional expressions - and conditional expressions come in very useful when adding control routines to your code. Control routines check for the existence of certain conditions, and execute appropriate program code depending on what they find.
The first - and simplest - decision-making routine is the "if" statement, which looks like this:
if (condition)
{
do this!
}
The "condition" here refers to a conditional expression, which evaluates to either true or false. For example,
if (car brakes fail)
{
start praying
}
or, to put it in language C# understands:
<%
if (brake == 0)
{
pray();
}
%>
If the conditional expression evaluates as true, all statements within the curly braces are executed. If the conditional expression evaluates as false, all statements within the curly braces will be ignored, and the lines of code following the "if" block will be executed.
Let's take a quick example:
<script language="c#" runat="server">
void Page_Load()
{
// temperature
int temp = 40;
if (temp > 35)
{
message.Text = "Man, it's hot out there!";
}
}
</script>
<html>
<head><title>Weather Forecast</title></head>
<body>
<asp:label id="message" runat="server" />
</body>
</html>

In this case, a variable named "temp" has been defined, and initialized to the value 40. Next, an "if" statement has been used to check the value of the "temp" variable and display a message if it's over 35. Note my usage of the greater-than (>) conditional operator in the conditional expression.
An important point to note - and one which many novice programmers fall foul of - is the difference between the assignment operator (=) and the equality operator (==). The former is used to assign a value to a variable, while the latter is used to test for equality in a conditional expression.
So
<%
a = 47;
%>
assigns the value 47 to the variable "a", while
<%
a == 47
%>
tests whether the value of "a" is equal to 47.
Next: Do It Or Else... >>
More ASP.NET Code Articles
More By Harish Kamath (c) Melonfire