[Reading Notes] C # Chapter 2 core C #,

Source: Internet
Author: User
Tags case statement

[Reading Notes] C # Chapter 2 core C #,

(1) The first C # Program

Create a console application, enter the code, and then click F5.

Console. WriteLine (); the meaning of this statement: output the content in the brackets to the interface;

Console. ReadKey ();

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6  7 namespace ConsoleApp1 8 { 9     class Program10     {11         static void Main(string[] args)12         {13             Console.WriteLine("Hello World");14             Console.ReadKey();15         }16     }17 }

After you click F5, the output page is displayed as follows:

Briefly explain the above Code:

  • C # end with a semicolon;
  • Use braces ({}) to construct a block of statements;
  • C # case sensitive.

 

(2) variables

Use the syntax to declare a variable in C #: first, the variable type, then space, then the variable name, and finally end with a semicolon.

Example:

The following statement declares a variable named x with the int type.

int x;

Example:

The following statement declares both the x and y variables. The type variables are int types at the same time.

int x,y;

 

1. Type Initialization

C # the compiler must initialize the variable with an initial value before referencing the variable in the operation.

Example:

The following statements initialize the declared variables (assign values)

int x = 10;int y = 20, z = 30;

Example:

The following statement fails to call the variable without initialization (the compiler reports an error)

int x;Console.WriteLine(x);

The preceding statement can run normally only when it is changed to the following statement:

int x = 10;Console.WriteLine(x);

 

2. type inference

Type inference uses the var keyword. Initialization is required when using the var keyword for variable declaration, because the compiler needs to deduce the type based on the value assignment.

Example:

The following two statements are equivalent.

int x = 10;var x = 10;

 

3. Scope of Variables

The scope of a variable is the code area that can access the variable. Generally, determining the scope follows the following rules:

  • As long as the class is in a specific scope, its fields (also become member variables) are also within the scope;
  • Local variables exist in the scope before the block statement or method that declares the variable ends;
  • Local variables declared in for, while, or similar statements exist in the loop.

4. Constants

A constant is a variable whose value does not change during use. The key word of a constant is const.

Example:

The following Code declares a constant named.

const int a = 10;

Constants have the following features:

Constants must be initialized during declaration. Once the value is specified, it cannot be rewritten.

The constant value must be used for computation during compilation.

Constants are always static.

 

(3) predefined Data Types

1. Value Type and reference type

Conceptual differences: the value type stores its value directly, and the reference type stores the reference of the value.

Differences in memory storage: The value type is stored in the stack, and the reference type is stored in the managed stack.

Example:

Because int is a value type, the following statement stores the value 20 in two places in the memory.

int x = 20;int y = 20;

Suppose we have defined a class (reference type) People with an Age attribute of the int type.

1 People people1 = new People (); 2 people1.Age = 20; 3 People people2 = people1; 4 Console. writeLine ("value of people2.Age before people1.Age is modified:" + lele2.age); 5 lele1.age = 21; 6 Console. writeLine ("the value of people2.Age after people1.Age is modified:" + people2.Age); 7 8 Console. readKey ();

Run the above Code and the result is as follows:

Based on the above results, we can see that the modification of people1.Age has an impact on people2.Age. This is because the reference type storage is a reference. When people1 is assigned to people2, people1 and people2 point to the same reference. As long as one of them modifies the reference content, all variables pointing to the reference will be modified.

 

2. predefined value types

1. Integer

C # Eight predefined integer types are supported

Name

CTS type

Description

Range

Type suffix

Sbyte

System. SByte

8-bit signed integer

 

 

Short

System. Int16

16-bit signed integer

 

 

Int

System. Int32

32-bit signed integer

 

 

Long

System. Int64

64-bit signed integer

 

L

Byte

System. Byte

8-bit unsigned integer

 

 

Ushort

System. Uint16

16-bit signed integer

 

 

Uint

System. Uint32

32-bit signed integer

 

U

Ulong

System. Uint64

64-bit signed integer

 

UL

2. Floating Point Type

Name

CTS type

Description

Number of digits

Range

Type suffix

Float

System. Single

32-Bit Single-precision floating point number

7

 

F

Double

System. Double

64-bit double-precision floating point number

15/16

 

 

3. decimal type

The decimal type is a high-precision floating-point number. The number of decimal digits can be customized by users. However, since decimal is not a basic type, performance loss occurs During computation.

Name

CTS type

Description

Number of digits

Range

Type suffix

Decimal

System. Decimal

High-precision floating point number

28

 

M

4. bool type

Bool and integer values cannot be implicitly exchanged. 0 cannot be used to indicate False or non-zero to indicate True.

Name

CTS type

Description

Range

Bool

System. Boolean

High-precision floating point number

True/false

5. Character Type

To save the value of a single character, C # supports the char data type.

Name

CTS type

Value

Char

System. Char

Represents a 16-bit (Unicode) character

 

3. predefined reference types

C # two predefined reference types are supported.

Name

CTS type

Description

Object

System. Object

Root type. Other types in CTS are derived from it (including value type)

String

System. String

Unicode string

There are some differences between string and common behaviors of reference types. For example, strings cannot be changed.

Example:

String str1 = "string 1"; string str2 = str1; Console. writeLine ("str2 value before str1 modification:" + str2); str1 = "string 2"; Console. writeLine ("the value of str2 after str1 is modified:" + str2 );

Run the code and the result is as follows:

We can see that str1 does not modify str2. The reason for this is: although the string is a string, it cannot be changed. When we modify str1, A New string object will be reassigned in the heap.

 

(4) Traffic Control

They are not executed in the order where the code is arranged in the program.

1. Condition statements

The condition statement can control the Execution Branch of the code based on whether the condition is met or the value of the expression.

1. if statement

Test whether the specified conditions are met

Example:

The following code runs the code in curly brackets when the condition is met:

If (condition ){}

Example:

The following code sets multiple conditions at the same time. when the conditions are met, the code in the braces corresponding to the corresponding position is run.

Int I = 0; if (I <= 0) {Console. writeLine ("Run [if (I <= 0)] Location Code");} else if (I <= 1) {Console. writeLine ("Run [else if (I <= 1)] Location Code");} else {Console. writeLine ("Run [else] Location Code ");}

Run the code. The result is as follows:

Note:

  • The condition expression in if brackets must be a Boolean value;
  • The program only runs the code that first meets the conditions from top to bottom.
  • The number of else if statements added to the if clause is not limited, but the number of else statements can only be 0 or 1

2. switch statement

The switch... case statement is suitable for selecting an Execution Branch from a group of mutually exclusive branches.

Example:

The following code runs the code in the recent break and above sections of this case when I satisfies the post-case value.

int i = 0;switch (i){    case 0:        Console.WriteLine("i=0");        break;    case 1:        Console.WriteLine("i=1");        break;    case 2:        Console.WriteLine("i=2");        break;    default:        break;}

Run the code. The result is as follows:

Note:

  • Case values cannot be the same and must be constant expressions. Variables cannot be used.
  • The case clause can be empty (without running code or break), and you can directly jump to the next case.
  • The discharge sequence of the case clause is irrelevant.
  • The case value can be a string.

 

2. Loop

C # provides four different loop mechanisms (for, while, do... while, and foreach). You can execute code blocks repeatedly before the conditions are met.

1. for Loop

The C # for Loop provides an iteration Loop Mechanism to test whether a condition is met before the next iteration is executed. Syntax:

For (initiator; condition; iterator ){}

Initializer: The expression to be calculated before the first loop is executed.

Condition: the expression to be tested before each execution of a new loop. When the expression is false, the iteration stops.

Iterator: The expression to be calculated after each iteration

A for Loop is a pre-test loop. The for loop is very suitable for the number of times that a statement or statement block repeats. Typical usage:

for (int i = 0; i < 10; i++){    Console.WriteLine(i);}

Run the code and the result is as follows:

2. while Loop

The for loop is the same, while is also a pre-test loop. The syntax is as follows:

While (condition ){}

The while LOOP applies to: Before the loop, do not know the number of times to be repeated

Example:

Bool condition = true; while (condition) {Console. WriteLine ("loop content"); condition = false ;}

Run the code and the result is as follows:

3. do... while loop

Do... while loop is the post-test version of while loop. Do... the while loop is applicable to the situations where the loop body must be executed at least once:

Example:

Bool condition = false; do {Console. WriteLine ("loop content") ;}while (condition );

Run the code and the result is as follows:

4. foreach Loop

A foreach loop can iterate every item in a set (now you don't have to consider the concept of a set, knowing that a set is something that contains a bunch of things ).

Example:

We assume that CustomerList is a set.

foreach (var item in CustomerList){    Console.WriteLine(item);}

 

3. Jump statement

1. goto statement

Poor reputation

2. break statement

Break is used to exit a case statement in for, foreach, while, or do... while, and switch statements.

3. continue statement

Continue is used to exit the current iteration for, foreach, while, or do... while, and start to execute the next iteration, not to exit the loop (exit the loop is what break does)

4. return Statement

The return statement is used to exit the class method and control the caller of the return method.

 

(5) Enumeration

Enumeration is a user-defined Integer type. Enumeration makes the code easy to maintain, clear, and easy to input. Declaration method:

Example:

public enum TimeOfDay{    Morning = 0,    Afternoon = 1,    Evening = 2}

We use the above enumeration in the switch statement:

TimeOfDay timeOfDay = new TimeOfDay();switch (timeOfDay){    case TimeOfDay.Morning:        Console.WriteLine("Morning");        break;    case TimeOfDay.Afternoon:        Console.WriteLine("Afternoon");        break;    case TimeOfDay.Evening:        Console.WriteLine("Evening");        break;    default:        break;}

You can obtain the enumerated string representation:

TimeOfDay timeOfDay = new TimeOfDay();Console.WriteLine(timeOfDay.ToString());

Run the code and the result is as follows:

Obtain the enumerated values from the string:

TimeOfDay timeOfDay = (TimeOfDay)Enum.Parse(typeof(TimeOfDay), "afternoon", true);

 

 

(6) namespace

The namespace provides a way to organize related classes and other types. Unlike a file or component, a namespace is a logical combination, not a physical combination.

Obviously, the namespace is sometimes quite long and tedious to input. In this case, you can list the class namespace at the top of the file to reduce the input:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

The alias of The namespace. The using keyword is used. The syntax is as follows:

using Sy = System;

 

 

(7) Main method

C # The program runs from the method Main (). This method is a static method of the class and structure, and the return type can only be int and void.

 

(8) compile more C # files

If you want to obtain a non-executable file (such as DLL) that can be loaded by the. NET Runtime Library, you must compile it into a library.

 

(9) Use comments

Single line comment //... the syntax is as follows:

// This is a single line comment

Multi-line comment/**/. The syntax is as follows:

/* This is the second line of the first line of multi-line comment */

 

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.