Later Today: ASP.NET Tutorial 2: Introduction to C#

ASP.NET Tutorial 4: Conditionals ( if/else constructs )

A statement and it’s block together are known as a construct.

This is an if statement:

(C#) if Statement:
if(strMyHair=="brown")

This is a block:

(C#) Code Block:
{
	string strBleach = "blonde";
	strMyHair = strBleach;
}

An if statement MUST have a code block following it – either one by itself will not work. Together, the statement and a block form a construct:

(C#) if Construct:
if(strMyHair=="brown")
{
	string strBleach = "blonde";
	strMyHair = strBleach;
}

This article will introduce you to conditionals in C#. Conditionals are a program’s decision-makers. They are used to evaluate and compare data, and then take different sets of actions based on the evaluations. It’s really not very different from the way humans make decisions. For instance, let’s say you’ve decided that you want go swimming… but only if it’s not too cold outside (because I live in sunny California, I’d consider anything 75 or under is “too cold”). If you can phrase a concept like that in English ("if it’s over 75 degrees outside, I’ll go swimming"), you can program it just as easily.

Hopefully by the end of this article you will be able to write some of the most basic conditionals in C#… if constructs. We’ll even cover some of the more fancy variations of if… including if else and if else if constructs.

> Operators and Evaluations

Introduces evaluations and introduces some new operators used in evaluations.

> Intro to Conditionals ( the if construct )

Introduces the basic if construct for making simple decisions in C#.

Conditionals are a kind of statement that can be use to evaluate data, and make decisions based on how the evaluation turned out. These conditional statements are usually followed by a block that contains the code to run when the statement makes a decision (the statement and block together is known as a construct).

It’s not nearly as confusing at it sounds, let’s use a practical example to demonstrate…

For example, let’s say you wanted to go swimming in your pool – but only if it was warm enough. Your decision making process might go something like this…

If the temperature is warm enough (over 75F), I will go swimming.

Essentially, you are evaluating the temperature to determine if it meets your idea of “warm enough”. Code works exactly the same way… you evaluate conditions then make a decision based on that evaluation. The above logic can easily be turned into code, like so…

(C#) Basic if Construct:
//dTemp is set to whatever the current temperature is outside
if( dTemp > 75 )
{
   GoSwimming();
}

Simple, right? In the above example, if dTemp had a value greater than 75, then the method GoSwimming() would be run. BUT, if dTemp did NOT have a value greater than 75, then the code inside the block would be skipped and GoSwimming() would NOT be run.

Note: When using > or < operators, it’s important to remember that the values cannot be equal or the evaluation will fail. In the above example, if dTemp was exactly 75, the evaluation would return false (because 75 is equal to 75, not greater than 75). However, if dTemp were 75.001, the evaluation would return true (because 75.001 is greater than 75).

For reference, all if constructs follow this basic formula…

(C#) if Construct Formula:
if ( [evaluation] )
{
   [Code to run when evaluation is true]
}

Note: When using if statements, the evaluations inside the parentheses are ALWAYS treated like yes/no questions. In other words, they must always evaluate to either true or false.

Using our previous swimming example… if dTemp has a value of 88, then the evaluation is true (ie: dTemp IS greater than 75) and so the code inside the if block will be executed. However, if dTemp has a value of 20, then the evaluation (dTemp > 75) would be false since 20 is not greater than 75, and so the code inside the block would be skipped.

> if-else

Expands on the previous section by showing how to force alternative code to run when an if statement’s evaluation returns false.
In our previous examples, any time dTemp is too cold (under 75), nothing happened. But what if we wanted to do something else if the evaluation returns false (instead of nothing at all)? Do you need to write another if construct? Nope… you simply need to add an else block immediately after the if block.

By using an else construct, whenever the if block’s evaluation returns false, the code inside the else block will be run instead.

So let’s build on our previous examples. Let’s say that any time it’s too cold for swimming, we’ll make hot cocoa instead. This way, no matter what the temperature is you’ll either go swimming or make hot cocoa (as opposed to swimming or nothing). Our code for this situation might look like this…

(C#) Basic if/else Example:
if( dTemp > 75 )
{
   GoSwimming();
}
else
{
   MakeCocoa();
}

That’s it.

Should the if evaluation return false, we’ll run whatever code is within the else block instead (in this case, it would be MakeCocoa()).

> if, else-if, else

Expands on previous sections by showing how to create multiple alternative if statements (called else if) in a single construct.
But what if we wanted to evaluate more than just the one statement? Let’s assume that you still want to go swimming if the temperature is over 75, but you’ll settle for the spa if the temperature is over 55 (assuming it’s too cold for swimming, of course). If it’s too cold for either of those, you’ll simply make hot cocoa instead. For this situation, you’re code might look like this:

C#:
if( dTemp > 75 )
{
   GoSwimming();
}
else if( dTemp > 55 )
{
   GetInSpa();
}
else
{
   MakeCocoa();
}

You can use as many else if blocks as you need.

Note: When using else if statements, C# will only evaluate the first code block that evaluates to true. If none of the blocks evaluate true, then the code inside the else block will be run instead. If you don’t want that to happen, simply leave off the else block… should none of the if or else if evaluations return true nothing will be run (just like a if construct).

> Evaluating Multiple Conditions (Simple)

Demonstrates how to use multiple conditions in a single if statement’s evaluation.
As I mentioned earlier, you can check multiple conditions within the same evaluation. To do this, you need to remember two additional operators…

Operator Meaning Description
&& and The previous condition AND the next condition must be met or the entire evaluation returns false.
|| or The previous condition OR the next condition must be met or the entire evaluation returns false.

So let’s say you only wanted to go swimming if the weather is warm enough AND only if your girlfriend agreed to go skinny dipping with you. Your code might look like this…

(C#) Simple if Construct:
if( dTemp > 75 && bGfSkinnyDip == true)
{
   GoSwimming();
}

The && operator in the above example would mean that GoSwimming() only runs if both dTemp is greater than 75 AND bGfSkinnyDip equals true.

If dTemp were 76 but bGfSkinnyDip was false, the code block would be skipped, because the && operator requires that BOTH conditions be true.

Alternatively, if you use the || operator, the entire evaluation will be considered true if either of the conditions are met. In the below example, GoSwimming() will be executed even though it’s too cold…

(C#) Simple if Construct:
double dTemp = 68; //It's 68 degrees
bGfSkinnyDip = true;//But the gf wants to skinny dip

if( dTemp > 75 || bGfSkinnyDip == true)
{
   GoSwimming(); //So we go swimming in the cold
}

> Evaluating Multiple Conditions (Advanced)

Builds on previous example by demonstrating more complex uses of multiple conditions.
But what if you want to make some more complicated evaluations? For instance, what if you wanted to check if two conditions were true OR two other conditions were true? Simple, just use parentheses to "group" the related evaluations together.

This works just like high school algebra. Whatever is inside the parentheses will be evaluated first (so that what’s inside the parentheses becomes a single true/false value)… then whatever is outside the parentheses is evaluated (comparing the new values).

So let’s assume that you will be willing to go swimming if:
• It’s warmer than 75 outside and the girlfriend wants to skinny dip.
OR
• It’s warmer than 60 outside and the pool water is warmer than 80.

Your code might look like this…

C#:
if( (dTemp > 75 &&  bGfSkinnyDip == true)
    || (dTemp > 60 && dWaterTemp > 80)
  )
{
   GoSwimming();
}

This is a good way to save space, since if you have multiple conditions that would execute the same code, you simply put all the conditions into the same evaluation instead of writing a whole slew of if blocks that run the same code. Here’s another way this might be used…

C#:
if( bIsMarried
    || bIsDating
    || iMistresses > 0
    || bIsEngaged)
{
   bIsInRelationShip = true;
}

Note: In the above example, notice how I didn’t bother writing bIsMarried == true. Booleans (which I always name with a lower-case "b" prefix) already have a true/false value, so you don’t need to fully evaluate them. In an evaluation, booleans can always be used by themselves.

No Comments

Post a Comment

You must be logged in to post a comment.

RSS Twitter LinkedIn Facebook
Doing neato things with JavaScript, please wait...