This is my learning note. The latest version is published in "CSharp syntax basics.
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 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: CS uses the data type in the. net FrameWork library.
Sbyte = System. SByte ,...
Description of Type bytes
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
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
Boolean is true or false. // only values true and false are allowed. 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; // not initialized outside the loop
For (I = 0; I <10; I ++)
{
Text = "Line" + Convert. ToString (I); // The value 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
{
Public static int x; // static variable. It 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 a, 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. Enumeration Value
Namespace Ch05Ex02
{
Enum orientation: byte
{
North = 1,
South = 2,
East = 3,
West = 4
}
/// Class1's Desciption
Class Class1
{
Static void Main (string [] args)
{
Byte directionByte;
String directionString;
Orientation myDirection = orientation. north;
Console. WriteLine ("mydirection = {0}", myDirection );
Direbybyte =
(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 ();
// Because not only the enumerated variable value is converted to the string variable, the string (mydirection) cannot be used );
// The Reverse conversion command is orientation myDirection =
(Orientation) Enum. Parse (typeof (orientation), myString );
String, so 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 Method 2 variable type 2 variable name 2;
...
}
Structure name structure variable name;
Structure variable name. Enumeration 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 loop to. Length
For (I = 0, I <friendNames. Length, I ++)
{
Console. WriteLine (friendNames [I]);
}
B. Foreach for read-only access
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 = {''}; // sets the delimiter
String [] myWords = myString. Split (separator); // separate them into arrays.
Console. WriteLine ("myString have {0} chars", myString. Length );
MyString = myString. ToLower (); // lowercase
MyString = myString. ToUpper (); // convert to uppercase
MyString = myString. Trim (); // Trim Spaces
MyString = myString. TrimStart (); // spaces before deletion
MyString = myString. TrimEnd (); // spaces 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 (digit, character); // Add the specified character to the specified Digit
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 sign of the prefix, the plus sign of the prefix, the plus sign of the one dollar, and the minus sign of the plus sign of the minus sign-
Displacement OPERATOR: <,>
Comparison OPERATOR: less than <greater than> less than or equal to <= greater than or equal to> =
Comparison OPERATOR: = ,! =
Logical operators :&
Logical OPERATOR: ^
Logical OPERATOR: |
Logical operators :&&
Logical OPERATOR: |
Comparison OPERATOR: equal to = * =/= % = + =-= <<=>>=<=^= | =
Suffix ++ and --
Vi. namespace
Using system; // system is the root namespace Of the. net FrameWork application. Then, the code in system can be referenced in the global namespace.
Namespace name
{
Using space name 2. Code 2; // then Code 2 can be directly referenced in code 1
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)
{
Case result 1:
Code 1;
Break;
Case result 2:
Code 2;
Break;
Case result 3:
Code 3;
Goto Case result 2; // At this time Case... is equivalent to a Label
Case Result 4:
Code 4;
Return;
Case result 5:
Case result 6:
Case result 7:
Code 567; // It can be executed as long as one of the above 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 ";
Alternatively, you can use the 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 must be
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 to jump 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 value; // return must be processed before the end of the function and cannot be skipped.
// Return; // when used for 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 Transfer parameter/reference transfer parameter/out output parameter
Static void showDouble (ref int val) // reference the transfer 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 parameters
{
Val * = 2;
ValIndex ++;
Console. WriteLine ("val doubled = {0}", val );
}
Int myNmuber = 5;
ShowDouble (ref myNumber); // The parameter passed by reference changes the value of myNumber. Therefore, myNumber must not be a constant or an uninitialized variable.
ShowDouble2 (myNumber); // pass the parameter value without changing the value of myNumber
Int valindex; // output parameter, which does not need to be initialized. The value is also lost when the function is executed.
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 a function command line parameter.
Static int Main () // returns an int value indicating the function termination state.
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 Name
{
// Class member
}
Internal/public
Sealed/abstract
10. Interfaces
Interface IMyInterface
{
// Interface member
}
This is my learning note. The latest version is published in "CSharp syntax basics.