Core C # -- C # advanced programming Chapter 2

Source: Internet
Author: User

Note: This article is intended for those who are not familiar with C # or who want to learn more about C #. If you are a technical expert, Please bypass it to avoid delay in your valuable time.

To use C #, first understand the knowledge: declare variables, initialization and scope of variables, pre-defined data types of C #, use condition statements, loop statements, and jump statements in C # programs to specify execution streams, enumerations, namespaces, main () method, basic command line C # compiler options, use System. console executes Console I/O, uses internal comments and documentation functions, pre-processor commands, and C # programming recommendation rules and conventions. The basic knowledge of C # is the foundation for using C # To develop programs later. After reading this chapter, readers will have enough C # knowledge to compile simple programs, however, inheritance and other object-oriented features cannot be used. These contents will be described later.

1. Simple C # Program

1. Enter the following code in the text editor and save it as a. cs file, for example, First. cs.

 1 using System;
2
3 namespace Wrox
4 {
5 public class MyFirstClass
6 {
7 static void Main()
8 {
9 Console.WriteLine("Hello World!");
10 Console.ReadLine();
11 return;
12 }
13 }
14 }

2.run the csung command line interpreter (csc.exe) on the source file. Compile this program: The csc First. cs program will generate the first.exe file under the corresponding directory. Double-click the file to display Hello World in the editor!

Ii. Variables

1. declare a variable in C # using the following syntax: datetype identifier, such as int I; declares the int variable I. The Compiler does not allow this variable to be used in expressions, unless this variable is initialized with a value.

2. After declaring I, you can use the assign operator (=) to assign a value to it: I = 10; you can also declare a variable in a line of code and assign a value: int I = 20;

3. Declare and initialize multiple variables of the same type in a statement: int I = 1, j = 2;

4. type inference uses the var keyword. In this case, the compiler can deduce the type of the variable based on the initial value of the variable. For example, var someNum = 100; equivalent to int someNum = 100;

Once the type is declared, the type cannot be changed, and other variables must follow the strongly typed rules.

5. The scope of the variable is the code area that can access the variable. Once the variable is out of the region, the variable cannot be used.

6. A constant is a variable whose value does not change during use. You can add the keyword const before the variable to specify the variable as a constant. Const int a = 100;

Constants must be initialized during Declaration;

The value of a constant must be used for computation during compilation and cannot be extracted from a variable to initialize a constant. If so, use a read-only field;

Constants are always static. Do not use static to modify const constants.

Iii. predefined Data Types

1. Value Type and reference type: in terms of concept, the difference is that the value type stores its value directly, and the application type stores Reference to the value.

2. CTS type: When C # declares an int type, it is actually an instance of System. Int32 in the. Net structure.

3. pre-defined value type: the built-in CTS value type indicates the basic type, such as integer, floating point, complex, and boolean type.

Such as: sbyte-System.SByte, short-System.Int16, int-System.Int32, long-System.Int64, byte-System.Byte, ushort-System.UInt16, uint-System.UInt32, ulong-System.UInt64, float-System.Single, double-System.Double, decimal-System.Decimal.

4. predefined reference types:

Object-System.Object is the base type of all types, and all other types are inherited directly or indirectly from the object;

String-System.String.

Iv. Flow Control-control flow statements

1. Condition Statement: if... else; switch... case statement;

2. Loop statement: for Loop; while loop; do... while loop; foreach loop;

3 jump statement: goto statement; break statement; continue statement; return statement;

5. enumeration-modified with enum

Enumeration is a user-defined Integer type. Creating enumeration makes the code easier to maintain and helps to specify valid and expected values for the variable. Enumeration makes the code clearer, descriptive names are allowed to represent integer values. Simple application:

 1 class EnumExample
2 {
3 public enum TimeOfDay
4 {
5 Morning=0,
6 Afternoon=1,
7 Evening=2
8 }
9 public static int Main()
10 {
11 WriteGreeting(TimeOfDay.Morning);
12 return 0;
13 }
14
15 static void WriteGreeting(TimeOfDay timeOfDay)
16 {
17 switch(timeOfDay)
18 {
19 case TimeOfDay.Morning:
20 Console.WriteLine("Good Morning");
21 break;
22 case TimeOfDay.Afternoon:
23 Console.WriteLine("Good Afternoon");
24 break;
25 case TimeOfDay.Evening:
26 Console.WriteLine("Good Evening");
27 break;
28 defult:
29 Console.WriteLine("hello!");
30 break;
31 }
32 }
33 }

C # the true strength of enumeration is that they will be instantiated in the background as a structure derived from the base class System. Enum, indicating that they can call methods and execute useful tasks. In fact, once the code is compiled, enumeration becomes the basic type, similar to int and float.

You can obtain the enumerated values from the string. See the following code:

1 TimeOfDay time = (TimeOfDay)Enum.Parse(typeof(TimeOfDay),"afternoon",true);
2 Console.WriteLine((int)time);

This will return 1, Enum. Parse () method to get the enumerated value from the string and convert it to an integer. The first parameter of Enum. Parse () is the enumeration type to be used, the second parameter is the string to be converted, and the third parameter specifies whether to ignore case sensitivity during conversion.

Vi. namespace

A namespace provides a way to organize related classes and other types. Unlike a file or component, a namespace is a logical combination rather than a physical combination. The namespace is separated by periods (.) and finally the class name. For example, System. Date. DbHelp. The namespace is introduced through the Using statement. For example, Using System. Date;

7. Main () method

C # The program runs from the method Main (). This method must be a static method of a class or structure, and its return value must be int, void, Main () the method either does not contain parameters or is a string-type array (string [] args ). It is not important to specify the level of the entry point method. Even if the method is marked as private, it can run.

8. Console I/O

Console. write (); Console. writeLine (); note that you can add a format string and an optional precision value. The main format strings are C: local currency format, D: decimal format, and E: scientific notation (the case of e determines the case of the index symbol), F: Fixed Point format, G: normal format, N: Use commas to represent the kilobytes, P: percent format, X: hexadecimal format. The output is as follows: ¥940.23, ¥940.2, and ¥940.2300.

1  decimal i=940.23m;
2 Console.WriteLine("{0:c}",i);
3 Console.WriteLine("{0:c1}",i);
4 Console.WriteLine("{0:c4}",i);

Another trick is to use placeholders to replace these format strings. The output is as follows:. 23.

1 double d = 0.234;
2 Console.WriteLine("{0:#.00}",d);

If there is no character at the position of the symbol (#), it will be ignored. If there is a character at the position of 0, it will be used instead of 0; otherwise, it will be displayed as 0.

9. Use comments

1. // This is a singleline comment

2./* This comment

Spans multiple lines */

3. XML document: // you can put the XML mark containing the document description of types and types in the code.

10. C # preprocessing commands: commands starting with # Are not converted into executable code, but may affect all aspects of the compilation process.

1. # define, # undef tells the compiler to exist or delete the symbols with a given name, which is usually used with # if;

2. # if, # elif, # else, # endif tell the compiler whether to compile a code block, such:

1 int DoSomeWork(double x)
2 {
3 #if DEBUG
4 Console.WriteLine("x is "+x);
5 #endif
6 }

This code will be executed as usual, but the Console. WriteLine command is included in the # if clause and is executed only after the # define command defines the symbol DEBUG. When the compiler encounters the # if statement, it first checks whether the symbol exists. if yes, it compiles the code in the # if statement. Otherwise, the compiler ignores all the code and knows that the matching # endif command is encountered.

3. # warning, # error: the compiler generates both warnings and errors when it encounters the @ warning command. If the compiler encounters the @ warning command, it displays the text following the @ warning command to the user, and then continues the compilation. If the compiler encounters the # error command, it will display the subsequent text to the user as a compilation error message and immediately exit the compilation without generating the IL code.
4. # region, # endregion: used to mark a piece of code as a block with a given name.

5. # line: used to change the file name and row number information displayed by the compiler in the warning and error messages.

6. # pragma: It can suppress or restore the specified compilation warning. # The pragma command can be executed at the class or method level. In the following example, the "field not used" Warning is disabled, and the warning is restored after MyClass class is compiled.

1 #pragma warning disable 169
2 public class MyClass
3 {
4 int neverUsedField;
5 }
6 #pragma warning restore 169

11. C # programming rules

1. rules for identifiers: identifiers are the names specified for variables, user-defined types, and members of these types. identifiers are case-sensitive. The identifiers in C # have two rules: it must start with a letter or underline and cannot use the C # keyword as an identifier.

C # Many reserved keywords are not listed here. If you need to use a reserved word as an identifier, you can add the prefix symbol @ before the identifier to inform the compiler that the subsequent content is an identifier, instead of the C # keyword, that is, the class is not a valid identifier, and the @ class is a valid identifier.

The identifier can also contain Unicode characters, which are specified by the syntax \ uXXXX. For example, \ u005fdentifier is a valid identifier.

2. Usage Conventions: Any development language has some traditional programming styles and is a convention.

In many cases, the name should be in PascaI case-sensitive format. Pascal case-means the first letter of a word in the name, such as EmployeeSalary, the names of all private member fields in the type must be in camel case and camel case.
The first letter of a name except the first word. For example, employeeSalary.

 

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.