ArticleDirectory
- 1.3.1 identifier
- 1.3.2 variables and Data Types
- 1.3.3 variable naming rules
Chapter 1 Program Design
"To become a real programmer, we need a baptism ."
"Program = Data Structure +Algorithm." Such a formula is very incisive. It directly describes the nature of the program beyond the surface layer. In addition, such a few simple words also let us understand "what should we learn ?". People have programs to do everything, but they are not aware of them. Some people list their daily actions in a table, which is "Program writing ".
The focus of this chapter:
◆ Identifier
◆ Variables and Data Types
◆ Variable naming rules
1.3 Variables
Variable isProgramming LanguageThe smallest logical unit in the program. variables are used to store temporary data generated when users use the application. These data are temporarily stored in the memory. To define a variable, you need to tell the memory what data type the variable is, as if in life, a cup (data type) name is called a milk cup (variable name) and is (=) liquid milk (temporary data ).
1.3.1 identifier
In C #, identifiers are used to declare variables, functions, and other user-defined object names. The length of an identifier can be 1 character or several characters. The identifier in C # can only contain uppercase letters, lowercase letters, underscores (_), numbers (0-9), and @ characters. It must begin with an uppercase letter, lowercase letter, or underline. It cannot start with a number, and the identifier cannot contain spaces. For example, a; Hello; color; _ color; this_is_valid and so on are all valid identifiers; 1 test; color. test; this is; $ test; If; Hello world and other strings cannot be used as identifiers.
The identifier is case sensitive. For example, the variable name and name indicate two different variables. However, we do not recommend that you use case-insensitive identifiers to represent two different identifiers. In most cases, identifiers should be well known.
The @ character can only be used as the first character of the identifier. The identifier with the @ prefix is called a verbatim identifier, which is useful when establishing interfaces with other programming languages, the character @ is not an actual part of the identifier. Therefore, this identifier may be considered as a normal identifier without a prefix in other languages. You can use the @ prefix with keywords for identifiers, such as @ class and @ bool. However, we do not strongly recommend that you do this. Here is an example:
1 using system;
2 namespace Microsoft. Example
3 {
4 public class testkeyword
5 {
6 static void main ()
7 {
8 @ class. @ static (true); // call a method defined using a keyword
9}
10 class @ Class // use the keyword class to define a class
11 {
12 public static void @ static (bool @ bool) // use the keyword static to define a method.
13 {
14 if (@ bool) // use the keyword bool to define a variable
15 {
16 system. Console. writeline ("the result is true"); // output the result
17}
18 else
19 {
20 system. Console. writeline ("the result is false"); // output the result
21}
22}
23}
24}
25}
Above Code , @ Appears in the C # identifier, but it is not part of the C # identifier. Therefore, the preceding example defines a class and contains a method named static and a parameter named bool. This facilitates cross-language transplantation. Because a word is reserved as a keyword in C #, but it may not be in other languages.
Final output result: True
Let's take a look at the following example:
Class Program
{
Public static void test (string @ Str)
{
System. Console. writeline (STR );
}
}
Of course, @ can also be added before non-keywords, so @ STR has no effect at all. @ STR is equivalent to STR, which is generally not encouraged.
A keyword is a predefined identifier reserved for the compiler. They cannot be used as identifiers in programs unless they have a @ prefix. For example, @ if is a legal identifier, and if is not a legal identifier, because it is a keyword.
Below is the list of C # keywords
Abstract event new struct
As explicit null Switch
Base extern object this
Bool false operator throw
Break finally out true
Byte fixed override try
Case float Params typeof
Catch for private uint
Char foreach protected ulong
Checked goto public unchecked
Class If readonly unsafe
Const implicit ref ushort
Continue in return using
Decimal int virtual
Default Interface sealed volatile
Delegate Internal Short void
Do Is sizeof while
Double Lock stackalloc else
Long static Enum namespace
String get partial set
Value where yield
What is a keyword? To help the compiler interpret the Code, some words in C # have special statuses and meanings. They are called keywords or reserved words ). Keywords provide specific syntaxes. the compiler uses these syntaxes to explain the expressions written by programmers. In the helloworld program, class, static, and void are all keywords.
The compiler uses keywords to identify the structure and organization of the Code. Since the compiler has a strict explanation of these words, the keywords can only be used according to the specific rules that can be recognized by the programming language. In other words, programming languages require developers to only place keywords in specific locations. Once a programmer violates these rules, the compiler reports an error.
1.3.2 variables and Data Types
The variable represents the actual storage location of the data. The data that each variable can store depends on its type. Before a variable is assigned a value, its type must be explicitly declared.
For example, the syntax format of variable Declaration
Data type variable name (identifier );
Data type variable name (identifier) = initial value;
The first definition method only declares a variable and does not assign values to the variable. In this case, the default variable is used. The second definition method initializes the variable, but note that the variable value should be consistent with the variable data type.
When assigning values to variables, temporary data is reasonably stored according to the corresponding data type. For example, a cup cannot be used to hold stones. At the same time, we must consider such a situation, now we have loaded milk into the milk cup. When the milk is used up, we can also use the milk cup to hold the cola. The temporary data has changed, but the data type has not changed because it is liquid, in this case, we get used to modifying the value of the variable milk cup or assigning a value to the milk cup again.
C # has seven types of variables: static variables, instance variables, array elements, value parameters, reference parameters, output parameters, and local variables.
For example:
Class
{
Public static int X;
Int y;
Void F (INT [] V, int A, ref int B, out int C)
{
Int I = 1;
}
}
X is a static variable, Y is an instance variable, V [0] is an array element, A is a value parameter, B is a reference parameter, and C is an output parameter; I is a local variable. This section briefly introduces various variables. For more information, see relevant chapters.
1. Static variables
Variables defined using the static modifier are called static variables. Static variables can only be accessed directly by class names and belong to class members.
2. instance variables
Variables that are not declared using the static modifier are called instance variables. When creating an instance of a certain type, the instance variables of this type are also generated. When there is no reference to this instance and the destructor of the instance is executed, this instance variable becomes invalid.
3. array elements
When an array instance is created, the element of this array is also created. When no reference to this array instance is provided, its element is invalid.
4. Value Parameters
As long as the parameter declaration without the ref modifier is used, it is called a value parameter. Whether the parameter is of the value or reference type.
5. Reference parameters
As long as the parameter declaration with ref modifier is called as a reference parameter. If it is a reference type, it is actually a reference.
6. Output Parameters
As long as the parameter declaration with the out modifier is used, it is called an output parameter. The output parameter itself does not create a new bucket. At the same time, the output parameter is similar to the reference parameter, but the output parameter can be used inside the method without initialization.
7. Local Variables
The variable declared in the method is called a local variable. It usually appears in the for loop statement or switch branch statement. When the control leaves the for loop statement or switch branch statement, the local variables in the statement become invalid.
Another important concept of variables is scope. The scope of a variable is the code area that can access the variable. Generally, the scope has the following rules:
1. If this variable is a field of the class, whether it is an instance variable or a static variable, this class is its scope. All code of this class accesses this variable.
2. If the variable is a local variable, the scope exists in closed curly braces of block statements or methods that declare the variable.
3. Local variables declared in for, while, or similar statements exist in the loop.
It is common for programs to use the same variable name for different variables in different sections. As long as the scope of the variable is different parts of the program, there will be no problem or ambiguity. Note that local variables with the same name cannot be declared twice in the same scope. Otherwise, the local variables will conflict with each other, so the following code cannot be used:
Int x = 20;
Int x = 30;
Consider using the following code:
Public static int main ()
{
For (INT I = 0; I <10; I ++)
{
Console. writeline (I );
} // Variable I is out of scope
For (INT I = 9; I> = 0; I --)
{
Console. writeline (I );
} // Variable I is out of scope
Return 0;
}
This Code uses a for loop to print data from 0 ~ And then print the number from 9 ~ 0. It is important that variable I in the Code is declared twice in the same method. The reason for doing so is that in the two declarations, I is declared inside the loop, so variable I is a local variable for the loop.
Let's look at another example:
Public static int main ()
{
Int J = 20;
For (INT I = 0; I <10; I ++)
{
Int J = 30; // compilation failed
Console. writeline (J + I );
}
Return 0;
}
If you try to compile it, it will produce an error. The local variable J cannot be declared twice in this scope, because it will give different meanings to the variable J.
1.3.3 variable naming rules
The naming rules are followed when writing code, which makes the program easier to understand and read. In addition, some functional information is also provided to help you understand the program. Some friends also know some naming rules, but the naming methods used during code writing often change, without a fixed style. The naming conventions of C # are summarized here to facilitate future queries.
Naming rules:
1. Try to use the same naming convention in all codes in the same technology.
2. Use official naming rules whenever possible.
3. Special Handling in special cases, but the reasons should be sufficient.
C # Language variables mainly use three naming methods: Hungary naming, camel naming, and Pascal naming.
Hungary naming: It is widely used in Windows Programming and proposed by a Microsoft Hungarian programmer. The Hungarian naming method identifies the scope and type of the variable by adding the symbol of the corresponding lowercase letter before the variable name as the prefix. For example, strname indicates that this is a string variable. In object-oriented programming, the Hungarian naming method is very awkward and rarely used. Currently, the only recommended place is the control variable name, for example, a button, we use btnsubmit to name the variable. This makes it clear that this variable is a button. For others, this variable is rarely used, because the IDE is very powerful and the prompt function is very powerful.
Camel naming method: the camel naming method, because the name using this naming method looks like a camel's camel. The camel naming method has two forms: the combination of uppercase and lowercase letters and words is underlined. For example, both firstname and first_name belong to the camel naming method, except for the first word, the first letter and other letters of all words are in upper case.
Use the camel case format: public class helloworld {...}
The Pascal naming method is similar to the camel naming method. However, all the first letters of the Pascal naming method are uppercase letters and the other letters are lowercase letters.
Use Pascal case: public class helloworld {...}
Below are some common naming rules for you:
1. Use Pascal's naming rules to name classes and methods.
Public class myclass
{
Public mymethod (){...}
}
2. Use camel naming rules to name parameters of local variables and methods.
Int number;
Void mymethod (string myname ){...}
3. Use I as the prefix when naming interfaces.
Interface imyinterface {...}
4. Use M _ as the prefix for private member variables.
Public class myclass
{
Private int m_number;
}
5. The custom attribute class uses attribute as its suffix.
6. The custom exception class uses exception as its suffix.
7. Use the phrase of the dynamic object structure during naming, for example, showdialog ().
8. A method with a return value should have a name that can describe its return value, for example, getobjectstate ().
9. Use meaningful variable names.
10. Declare variables using the C # language type instead of using its alias in the system namespace. For example:
Use object instead of Object
Use string instead of string
Use int instead of int32
11. Use meaningful namespaces, such as company names and product names.
12. Avoid using a fully qualified name. Replace it with the using statement.
13. Avoid writing the using statement inside the namespace.
14. Put all the namespaces defined by the Framework into one group, and put custom and third-party namespaces in another group.
15. Maintain a strict indent style.
16. Note indentation and encoding indentation must be at the same level when writing comments.
17. Declare it whenever possible when using a local variable for the first time.
18. The file name should reflect the class it contains.