Chapter 6 control statements of. net Programming pioneer C #

Source: Internet
Author: User

Chapter 6 control statements
There is a statement that you can find in each programming language control flow statement. In this chapter, I introduced the control statements of C #, which are divided into two main parts:
. Select statement
. Loop statement
If you are a C or C ++ programmer, a lot of information may make you feel similar. However, you must know that there are still some differences between them. </P> <P> 6.1 SELECT statement
When a SELECT statement is used, you define a control statement whose value controls which statement is executed. Two selection statements are used in C:
. If statement
. Switch statement </P> <P> 6.1.1 if statement
The first and most commonly used statement is the if statement. Whether the included statement is executed depends on the Boolean expression:
If (Boolean expression) Inclusion statement
Of course, there can also be else branches. When the value of a Boolean expression is false, the Branch will be executed:
If (Boolean expression) contains the else statement.
An example of checking a non-zero long string before executing some statements: </P> <P> if (0! = StrTest. Length)
{
} </P> <P> This is a Boolean expression. (! = Indicates not equal .) However, if you are from C or C ++, you may get used to writing code like this:
If (strTest. Length)
{
} </P> <P> This does not work in C #, because if statements only allow Boolean (bool) data type results, the Length attribute object of the string returns an integer ). The compiler will see the following error message:
Error CS0029: Cannot implicitly convert type int to bool (the int type Cannot be implicitly converted to bool .) </P> <P> the above is the habit that you must change, and the following will not cause a value assignment error in the if statement:
If (nMyValue = 5 )... </P> <P> the correct code should be </P> <P> if (nMyValue = 5 )... </P> <P> because equal comparison is implemented by =, it is like in C and C ++. Take a look at the following useful comparison operators (but not all data types are valid ):
==-- Returns true if the two values are the same.
! = -- Returns false if two values are different.
<, <=,>, >=-- Returns true if the link (less than, less than, or equal to, greater than, greater than, or equal to) is satisfied.
Each operator is executed through the overload operator, and such execution has a specification on the data type. If you compare two different types, there must be an implicit conversion for the compiler to automatically create the necessary code. However, you can execute an explicit type conversion.
The code in listing 6.1 demonstrates different use cases of the if statement and how to use the string data type. The main idea of this program is to determine whether the first parameter passed to the application starts with an uppercase letter, lowercase letter, or number. </P> <P> listing 6.1 determining the character form </P> <P> 1: using System;
2:
3: class NestedIfApp
4 :{
5: public static int Main (string [] args)
6 :{
7: if (args. Length! = 1)
8 :{
9: Console. WriteLine ("Usage: one argument ");
10: return 1; // error level
11 :}
12:
13: char chLetter = args [0] [0];
14:
15: if (chLetter> =)
16: if (chLetter <= Z)
17 :{
18: Console. WriteLine ("{0} is uppercase", chLetter );
19: return 0;
20 :}
21:
22: chLetter = Char. FromString (args [0]);
23: if (chLetter> = a & chLetter <= z)
24: Console. WriteLine ("{0} is lowercase", chLetter );
25:
26: if (Char. IsDigit (chLetter = args [0] [0])
27: Console. WriteLine ("{0} is a digit", chLetter );
28:
29: return 0;
30 :}
31 :}</P> <P> check whether the parameter array contains only one string at the first if language segment starting with row 7th. If the conditions are not met, the program displays usage information on the screen and stops running.
Multiple methods can be used to extract a single character from a string-the character index can be used as in row 13th, or the static FromString method of the Char class, which returns the first character of the string.
16th ~ 20 rows of if statement blocks use a nested if statement block to check uppercase letters. The logical "&" Operator (&) can be used to detect lower-case letters. Finally, you can use the static function IsDigit of the Char class to detect numbers.
In addition to the "&" operator, there is another conditional logical operator, which represents "|" of "or ". Both operators are short-circuited. For the "&" operator, it means that if the first result of the condition "and" expression returns a dummy value, the remaining condition "and" expression will no longer be evaluated. Correspondingly, the "|" operator is short-circuited when the first true condition is met.
What I want you to understand is that to reduce the computing time, you should put the expression most likely to make the value "Short Circuit" in front. You should also be aware that there is a risk of replacement for some values in the if statement. </P> <P> if (1 = 1 | (5 = (strLength = str. Length )))
{
Console. WriteLine (strLength );
} </P> <P> of course, this is an exaggerated example, but it illustrates the idea that if the first statement is evaluated as true, the second statement will not be executed, it enables the variable strLength to maintain the original value. Give everyone a piece of advice: never assign a value to an if statement with conditional logical operators. </P> <P> 6.1.2 switch statement
Compared with the if statement, the switch statement has a control expression and contains statements that run according to the constants of the control expressions they are associated. </P> <P> switch (control expression)
{
Case constant expression:
Containing statements
Default:
Containing statements
} </P> <P> the data types allowed by the control expression are sbyte, byte, short, ushort, uint, long, ulong, char, string, or enumeration type. As long as other data types can be implicitly converted to any of the above types, it is also good to use it as a control expression.
The switch statement is executed in the following sequence:
1. Evaluate the control expression
2. If the constant expression after the case label matches the value obtained by the control statement, the containing statement is executed.
3. If no constant expression meets the control statement, the statement contained in the default label is executed.
4. If there is no case tag and no default tag, the end of the switch CIDR block is switched.
Before proceeding to more details about the switch statement, see list 6.2, which shows how to use the switch statement to display the days of a month (ignore cross-year)
Listing 6.2 use the switch statement to display the number of days in a month </P> <P> 1: using System;
2:
3: class FallThrough
4 :{
5: public static void Main (string [] args)
6 :{
7: if (args. Length! = 1) return;
8:
9: int nMonth = Int32.Parse (args [0]);
10: if (nMonth <1 | nMonth> 12) return;
11: int nDays = 0;
12:
13: switch (nMonth)
14 :{
15: case 2: nDays = 28; break;
16: case 4:
17: case 6:
18: case 9:
19: case 11: nDays = 30; break;
20: default: nDays = 31;
21 :}
22: Console. WriteLine ("{0} days in this month", nDays );
23 :}
24 :}</P> <P>
The switch CIDR block contains 13th ~ 21 rows. For C programmers, this looks very similar because it does not use break statements. Therefore, there is a more vital difference. You must add a break statement (or a different jump statement) because the compiler will remind you that it is not allowed to go directly to the next part.
What is direct access? In C (and C ++), it is completely legal to ignore break and write the following code:
NVar = 1
Switch (nVar)
{
Case 1:
DoSomething ();
Case 2:
DoMore ();
} </P> <P> in this example, after the code of the first case statement is executed, the code of other case labels is directly executed, until a break statement exits the switch CIDR block. Although sometimes this is a powerful feature, it often produces hard-to-find defects.
But what if you want to execute code for other case labels? There is a way to display it in listing 6.3. </P> <P> List 6.3 use the goto label and goto default in the swtich statement </P> <P> 1: using System;
2:
3: class SwitchApp
4 :{
5: public static void Main ()
6 :{
7: Random objRandom = new Random ();
8: double dRndNumber = objRandom. NextDouble ();
9: int nRndNumber = (int) (dRndNumber * 10.0 );
10:
11: switch (nRndNumber)
12 :{
13: case 1:
14: // do nothing
15: break;
16: case 2:
17: goto case 3;
18: case 3:
19: Console. WriteLine ("Handler for 2 and 3 ");
20: break;
21: case 4:
22: goto default;
23: // everything beyond a goto will be warned
24: // unreachable code
25: default:
26: Console. WriteLine ("Random number {0}", nRndNumber );
27 :}
28 :}
29 :}</P> <P> in this example, the Random class is used to generate a value (7th ~ 9 rows ). The switch syntax contains two jump statements that are valid for the switch statement.
Goto case label: Jump to the label described
Goto default: Jump to the default tag
With these two jump statements, you can create the same functions as C, but direct access is no longer automatic. You must explicitly request it.
The deeper meaning of the direct function is that you can arrange tags at will, such as placing the default tag before all other tags. To illustrate this, I created an example to intentionally not end the loop: </P> <P> switch (nSomething)
{
Default:
Case 5:
Goto default;
} </P> <P> I have reserved the function of one of the swich statements until the end -- in fact, you can use strings as constant expressions. This may not sound like big news for VB programmers, but programmers from C or C ++ will like this new feature.
Now, a switch statement can check string constants as shown below. </P> <P> string strTest = "Chris ";
Switch (strTest)
{
Case "Chris ":
Console. WriteLine ("Hello Chris! ");
Break;
} </P> <P>
6.2 loop statements
When you want to execute some statements or segments repeatedly

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.