[C #] C # syntax basics-Conversion

Source: Internet
Author: User
I. Comments

 

/* The comment statement is included in "backslash *" and "* Backslash,

 

Or two backslash and line break,

 

Or among the three backslash and line breaks (which can be automatically recognized by vs as a file annotation for extraction)

 

Note that the '\' in the comment will comment out the next line together with the continued line operator. */

Static void main (string [] ARGs) {// The statement block is included in {}. Int myinterger; // The statement starts with; ends string mystring; /// ignore blank characters (Space/press enter/TAB) myinterger = 17 ;}

// Avoid annotation nesting errors. Use the # If, # endif pre-processing statement.

 

Ii. Data Types

 

1. Basic/internal user-defined

 

A. built-in type: Does CS use. NET Framework? Data Types in the database

 

Sbyte = system. sbyte ,...

 

Type Bytes Explanation
Byte 1 Unsigned byte type
Sbyte 1 Signed byte type
Short 2 Signed short-byte type
Ushort 2 Unsigned short-byte type
Int 4 Signed integer
Uint 4 Unsigned integer
Long 8 Signed long integer type
Ulong 8 Unsigned long integer
Float 4 Floating Point Number
Double 8 Double Precision
Decimal 8 Fixed precision
String ? Unicode string type
Char ? Unicode Character Type
Bool ? True and false Boolean Type // only true and false values are accepted. It does not accept any integer type.

 

B. User-defined types include:

 

Class)

 

Structure Type (struct)

 

Interface)

 

2. value types and reference types)

 

A, Value Type: memory is allocated in the stack sequentially. They include: all basic or built-in types (excluding the string type), structure type, enumeration type (Enum type)

 

B. Reference Type: memory is non-linear distributed in the heap. When they are no longer used, CS Automatically releases the memory through the garbage collector (C ++ uses delete ). They are created using the new operator.

 

The reference types include: class type, interface type, collection type such as array, string type, and enumeration type.

 

The schema is suitable for fast access and data types with a small number of members. If there are more involved, you should create a class to implement it.

 

3. Data Type Conversion

 

Implicit conversion: it is impossible to convert from low-precision conversion to high-precision conversion to Char. In addition, 0 can be implicitly converted to Enumeration type, but other integers cannot.

 

Explicit Conversion

Static void main (string [] ARGs) {short shortresult, shortval = 4; int integerval = 67; long longresult; float floatval = 10.5f; double doubleresult, doubleval = 99.999; string stringresult, stringval = "17"; bool boolval = true; console. writeline ("variable conversion examples \ n data type conversion example \ n"); doubleresult = floatval * shortval; console. writeline ("implicit,-> double: {0} * {1}-> {2}", floatval, shortval, doubleresult); shortresult = (short) floatval; console. writeline ("implicit,-> short: {0}-> {1}", floatval, shortresult); stringresult = convert. tostring (boolval) + convert. tostring (doubleval); console. writeline ("explicit,-> string: \" {0} \ "+ \" {1} \ "-> {2}", boolval, doubleval, stringresult ); longresult = integerval + convert. toint64 (stringval); console. writeline ("mixed,-> long {0} + {1}-> {2}", integerval, stringval, longresult );}

3. variables:

 

1. Common variables:

 

(1) Naming rules: letters, underscores (_), underscores (@), underscores (_), and numbers (/) are used to escape and @ is used to escape and specify one by one, @ it is often used to retain keywords to maintain compatibility with other languages)

 

(2) declare a variable: variable name of the variable type

 

Variable assignment: Variable = value to be assigned

 

C # variables must be initialized before being accessed; otherwise, an error will be reported during compilation. Therefore, it is impossible to access an uninitialized variable (such as an uncertain pointer and an expression that exceeds the array boundary ). Before using a variable, it is best to declare and initialize it first.

 

(3) C # does not have global variables or global functions. Global operations are implemented through static functions and static variables.

Int I; string text; // for (I = 0; I <10; I ++) {text = "line" + convert. tostring (I); // It is not initialized in the loop. When the loop is exited, the value is lost and the reference fails. Console. writeline ("{0}, text);} console. writeline (" Last txet output in loop: {0}, text); // error. The correction method is to initialize outside the loop: String text = "";

 

(4) Naming Conventions: simple use of camelcase and complex use of pascalcase?

 

(5) seven types of variables:

Class A {public static int X; // static variable, which is loaded from the class until the end of the program. Int y; // non-static variables, or instance variables, from class instance creation to instance space release. /* V [0] is an array element, A is a value parameter, B is a reference parameter, and C is an output parameter */void F (INT [] V, int, ref int B, out int c) {int I = 1; // local variable, not initialized c = a + B ++ ;//}}

2. Enumeration

Enum enumeration name: enumeration value type (default value: int, default value: 0, 1, 2 ...) {enumeration value 1 = ..., enumerated value 2 = ..., enumeration value 3, // if no value is assigned, the default value is the value of the last specific value + 1 ...} enumeration name variable name = enumeration name. enumerated value namespace ch05ex02 {Enum orientation: byte {North = 1, South = 2, East = 3, west = 4} // class1's desciptionclass class1 {static void main (string [] ARGs) {byte directionbyte; string directionstring; orientation mydirection = orientation. north; console. writeline ("mydirection = {0}", mydirection); directionbyte = (Byte) mydirection; // because Enum stores byte, it can be converted in turn in theory, but it is not necessarily logical. Mydirection = (orientation) mybyte; directionstring = convert. tostring (mydirection); // The equivalent command is directionstring = mydirection. tostring (); // The string (mydirection) cannot be used because not only the enumerated variable value is converted to the string variable; // The Reverse conversion command is orientation mydirection = (orientation) enum. parse (typeof (orientation), mystring); but because Enum does not necessarily save the string, an error may occur. For example, if the value of mystring is north, it cannot be mapped to the north in orientation. An error occurs. Console. writeline ("Byte equivalent = {0}", directionbyte); console. writeline ("string equivalent = {0}", directionstring );}}}

 

 

 

3. Structure

Struct structure name: {Access Mode 1 variable type 1 variable name 1; // access mode public/private access mode 2 variable type 2 variable name 2 ;...} structure name: name of the structure variable; Name of the structure variable. enumerated value = ...;

 

4. One-dimensional array

 

Variable type [] array name = new variable type [number of elements] {element 0, element 1, element 2 ...} // The number of elements must be an integer or an integer constant, and must be the same as the number of values in the subsequent element columns; otherwise, an error occurs. The new declaration of the number of elements and the values of the subsequent element columns can be selected to declare and initialize the array.

 

Traversal method

A, for loops. lengthfor (I = 0, I <friendnames. length, I ++) {console. writeline (friendnames [I]);} B. foreach performs read-only access to foreach (string listname in friendnames) {console. writeline (listname );}

 

5. Two-dimensional array (multi-dimensional)

 

Variable type [,] array name = new variable type [number of one-dimensional elements, number of two-dimensional elements] {element 00, element 01, element 02 ...}, {element 10, element 11, element 12 ...}...}

 

6. right-angle array (staggered array, array in the array)

 

7. String operations:

String mystring = "I Have a Dream. "; char mychar = mystring [2]; // use the string variable as a read-only char array, and cannot rewrite mystring [2] char [] mychars = mystring. tochararray (); char [] separator = {''}; // set the separator string [] mywords = mystring. split (separator); // separate them into an array console. writeline ("mystring have {0} chars", mystring. length); mystring = mystring. tolower (); // convert to lower case mystring = mystring. toupper (); // convert to uppercase mystring = mystring. trim (); // The space before and after deletion mystring = mystring. trimstart (); // space before deletion mystring = mystring. trimend (); // space after deletion mystring = mystring. padleft (number of digits); // Add spaces to the specified number of digits. mystring = mystring. padright (number of digits); // Add spaces to the specified number of digits mystring = mystring. padleft (number of digits, character); // prefix the specified character to the specified number of digits char [] trimchars = {"E", "#", "*"}; mystring = mystring. trim (trimchars); // delete a specified character

 

4. constants:

 

Const int inttwo = 2 (both values must be declared)

 

5. Operators: sorted by priority

Arithmetic Operators: The Plus (+) and the minus (--) operators with the same prefix as the plus (+) and minus (-) operators with the same prefix as the minus (*) operators: <, >> comparison operators: less than <greater than> less than or equal to <= greater than or equal to> = comparison operator: = ,! = Logical operator: & logical operator: ^ logical operator: | logical operator: & logical operator: | comparison operator: equal to = * =/= % = + =-= <= >>=<=^= | = suffix ++ and --

Vi. namespace

 

Using system; // is the. NET Framework? The application root namespace can then reference the code in System in the global namespace.

Namespace space name {using space name 2. Code 2; // you can then directly reference code 2 code 1 at code 1; namespace name 2 {code 2 ;}}

VII. Condition statements

 

A, if statement: general judgment

If (condition 1) Code 1; else Code 2; If (condition 1) {} else {}

B. Switch statement: used to judge multiple results under the same condition

Switch (condition) {case result 1: Code 1; break; case result 2: Code 2; break; case result 3: Code 3; goto case result 2; // case .. equivalent to a label case result 4: Code 4; return; case result 5: case result 6: case result 7: Code 567; // It is executed if one of the preceding three cases is met. Break;... Default: Code; break ;}

 

C, ternary operation statement: (condition )? True: false

 

Commonly Used in simple assignment statements: String mystring = (myinteger <10 )? "Less than 10": "Great than or equal ";

 

Or is it used to simply format a text statement: console. writeline? ("I am {0} year {1} old.", myinteger, myinteger = 1? "": "S ");

 

8. Loop statement:

 

A, do... while: loop when the condition is true.

Do {...} while (condition); // The semicolon cannot be missing

B, while...: loops when the condition is true.

While (condition ){...}

C, for...: Use counter loop.

For (variable; condition; Operation) // you can declare the variable at this time, but the scope is limited to within the loop. {... Break; // jump out of the entire loop return; continue; // stop the current loop and continue the next loop goto tag; // disable the use of goto inside the loop from outside the loop}

9. Functions

A, Function Definition: static return value type/void function name (parameter type 1 parameter 1, parameter type 2 parameter 2 ,...) {... return return value; // return must be processed before the end of the function. You cannot skip // return; // when using void, use return without return value to stop the function .}

B. Parameter array:

Static int sumvals (Params int [] Vals) {int sum = 0; foreach (INT Val in Vals) {sum + = val;} return sum ;} static void main (string [] ARGs) {int sum = sumvals (1, 5, 2, 9, 8); console. writeline ("summed values = {0}", sum);} C, value passing parameter/reference passing parameter/out output parameter static void showdouble (ref int Val) // reference the passing parameter {Val * = 2; console. writelie ("Val doubled = {0}", Val);} static void showdouble2 (INT Val) // value passing parameter {Val * = 2; console. writeline ("Val doubled = { 0} ", Val);} static void showdouble3 (INT Val, out int valindex) // output parameter {Val * = 2; valindex ++; console. writeline ("Val doubled = {0}", Val) ;}int mynmuber = 5; showdouble (ref mynumber); // reference the passing parameter and change the value of mynumber, therefore, mynumber must not be a constant or an uninitialized variable. Showdouble2 (mynumber); // value passing parameter, does not change the value of mynumber int valindex; // out output parameter, does not need to be initialized, and will also lose the value when the function starts execution. Showdouble3 (mynumber, out valindex );

D. Global Variables

 

Static/const variable name // The global variable defined by const is read-only

 

When a global variable has the same name as a local variable, the local variable takes priority. You must reference a global variable like class1.mystring.

 

E, main () function;

Static void main () Static void main (string [] ARGs) // ARGs is the FUNCTION command line parameter static int main () // returns an int value indicating the function termination status static int main (string [] ARGs) // returns an int value indicating the function termination status.

F: Functions in the Structure

 

G. overload of functions with the same name: the same name, different signatures, the system automatically identifies which function to use

 

H. Delegate: used to store references as functions to flexibly call Functions

 

10. Object-oriented Basics

 

11, Class

 

1. Class Definition

Class class name {// class member} internal/publicsealed/abstract

10. Interfaces

Interface imyinterface {// interface member}
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.