|
|
|
As we've already mentioned, computer languages are a little like human languages; there's many different ways to "say" the same thing; it just depends on what you're actually trying to accomplish. There is a variation on the "while" loop, and a variation on the "if" statement that we need to examine, in order to round out our understanding of flow control. The "while loop" variation isn't that big a deal; I'm mainly including it here so you know what it looks like: do { ++countB; } while( countB < 5 ); Functionally, it's almost the same as a normal "while" loop. We put a "do" keyword where the "while" used to be, and then move the actual "while" part below. And we put a semicolon after the "while" part, since it's no longer at the top. That's the only syntax difference. Both the "while" and "do while" loops will loop continuously until their Boolean expression becomes false. The difference is that the "while" loop checks its expression before its code runs, and the "do while" checks its expression after its code runs. So in a "while" loop, if the Boolean expression is already false when the loop starts, the code inside the loop will never run. Whereas in a "do while" loop, your code's guaranteed to run at least once. Here's an example of where you'd want this: string input = ""; do { Console.Write("Type some text, or leave it blank to quit: "); input = Console.ReadLine(); } while(input != ""); The example is a little abstract, but you can basically see that we're continuously using ReadLine() to set the value of "input", until the user leaves it blank. However, since the value of "input" starts out as blank, we use a do/while, so that the user has at least one chance to set the value to something else. In a normal "while" loop, the code in the loop would never get a chance to run, because the "while" would detect that "input" was blank, first. In all honesty, I still don't really use do/while for much, but at least now if you run into it, you'll know what it is. Our "if" statement variation is a little more bizarre looking, but it's also a little more useful. It's called the "switch" statement, and it's designed to replace the "if" statement in cases where there are multiple paths to take, based on the concrete value of one variable. Consider the following "if" statement... int month = 1; string monthName = ""; if( month == 1 ) monthName = "January"; else if( month == 2 ) monthName = "February"; else if( month == 3 ) monthName = "March"; ...and so on. Now, there's nothing technically wrong with the above logic, but there's an awful lot of repetition in the code, isn't there? We're testing the same number three times (probably twelve times, actually), and in every "else if", the only thing that's going to change is one little number. That's usually a good hint that it's time to whip out the "switch" statement. The following code does exactly the same thing as the above "if", but now it's written in "switch" form... switch( month ) { case 1: monthName = "January"; break; case 2: monthName = "February"; break; case 2: monthName = "March"; break; } I'll grant that its syntax looks different from the other statements we've been using, but the breakdown is actually quite simple. We begin with the "switch" keyword, and supply the name of the variable we're testing in the brackets. The rest of the "switch" statement is a simple list of different "cases". Each case begins with the "case" keyword, followed immediately by the actual value we want to test for, and a colon. Any number of code lines can follow, and when we're done, we terminate the case with the "break" keyword. The switch statement executes the same way as an "if". As soon as a matching case is found, the switch executes the code in that case, and skips all the other cases. The switch statement also has its own version of "else", as you can see here: switch( month ) { case 1: monthName = "January"; break; // The other 11 cases would go here default: monthName = "Invalid Month"; break; } "default" works exactly the same as "else", behaving as a "catch all" in case none of the specific cases were encountered. Due to the nature of their syntax, switch statements can only test equivalence ("greater than" and "less than" operators cannot be used). You can, however, have multiple cases run the same block of code by placing them one after another, with no code or "break" in-between: switch( month ) { case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: monthName = "Valid Month"; break; } Of course, if you need to do a lot of that, it's probably better to just go with an "if" statement, where you can use < and > to greater effect. By the way, if you only need one line of code in each case, you might consider doing this: switch( monthNum ) { case 3: Console.WriteLine("March"); break; case 4: Console.WriteLine("April"); break; case 5: Console.WriteLine("May"); break; case 6: Console.WriteLine("June"); break; } All the same code is still there; we've simply grouped each case's code into one line. This brings out an important point about C# coding in general. For the most part, line breaks and tabs are simply for looks and readability, and have nothing to do with the actual code. So in this case, if putting those three lines of code onto one line is more readable, than go ahead and do it! That leaves one last little detail. You've probably noticed that the individual cases are lacking the { } pairs that an "else" or "else if" would normally have. The only time you would actually need them is if you were going to declare a variable inside a case. In that situation, your code would look something like this: switch( monthNum ) { case 1: { Console.WriteLine("January"); int temperature = -20; break; } } So, now you know about "switch" statements (and "do while" loops, not you'll likely be needing them). The question is, when to use them, and why? Use a switch statement when you need to test for several possible values of the same variable ("month" is a great example of this). You may use switches on integers, strings, chars, and various enums (which you don't know about yet, but trust me, they're awesome). And why use them? Simply because they tend to be more readable than an "if" statement that does the same thing. Also, switch statements actually execute faster than "if" statements, because they are specific-purpose, which can add up to better performance if a piece of code is being run hundreds of times per second. It's best to use them when you have the opportunity. using System; namespace F_DoSwitch { class Class1 { [STAThread] static void Main(string[] args) { // Normal "while" loop int countA = 0; while( countA < 5 ) { ++countA; } // Alternative "do while" loop int countB = 0; do { ++countB; } while( countB < 5 ); Console.WriteLine("Count A = {0}, Count B = {1}", countA, countB); // "switch" statement Console.Write(Environment.NewLine + "Enter a month number: "); int monthNum = Convert.ToInt32(Console.ReadLine()); switch( monthNum ) { // Multiline, with { } braces case 1: { Console.WriteLine("January"); break; } // Multiline, without { } braces case 2: Console.WriteLine("February"); break; // Single line case 3: Console.WriteLine("March"); break; case 4: Console.WriteLine("April"); break; case 5: Console.WriteLine("May"); break; case 6: Console.WriteLine("June"); break; case 7: Console.WriteLine("July"); break; // Let several cases do the same thing case 8: case 9: case 10: case 11: case 12: Console.WriteLine("Other half of year."); break; // "Else" default: Console.WriteLine("Not a month!"); break; } // Prompt for exit Console.Write(Environment.NewLine + "Program complete! Hit enter to exit..."); Console.ReadLine(); } } } |
|