1. Constant: The amount at compile time when its value can be determined and the value does not change during program run.
In layman's terms, it defines a quantity that cannot be changed. Since the value cannot be changed, it must be initialized at the time of definition.
Syntax: const type-name Constant name = constant expression;
Example: const string cat= "Hello cat";
2. Variables: Objects with variable names and values
The variable is to temporarily store the data somewhere in memory in case of a call.
Declaration: [Access modifier] type variable name [= initial value] [variable name =[initial value] ...];
int int1,int2,int3=3,int4;
3. Scope of variables
Variables can use modifiers, and the following modifiers are available:
Public does not restrict access.
Protected is limited to the current class and derived classes only.
Internal access is limited to the current assembly.
Protected internal access is limited to the current assembly or from the currently derived class.
Private is limited to the current class.
In addition to the above modifiers, you can also use static (static) and readonly (read-only)
3. Naming conventions
Variable and method parameter naming: Variable description According to different data type prefix + First letter capitalization
Type |
Prefix |
Example |
Array |
Arr |
Arrshoppinglist |
Boolean |
bln |
Blnispostback |
Byte |
Byt |
Bytpixelvalue |
Char |
Chr |
Chrdelimiter |
Datetime |
Dtm |
Dtmstartdate |
Decimal |
Dec |
Decaverageheight |
Double |
Dbl |
Dblsizeofuniverse |
Integer |
Int |
Introwcounter |
Long |
Lng |
Lngbillgatesincome |
Object |
Obj |
Objreturnvalue |
Short |
Shr |
Shraverage |
Single |
Sng |
Sngmaximum |
String |
Str |
strFirstName |
Points:
1. Variables declared in the method body can not be decorated with access modifiers such as public private;
2. A variable declared in a class, called a field or member variable;
3. The variable name must be a letter or an underscore cannot have a special symbol at the beginning;
4. Variables can be declared multiple in the same statement, separated by commas;
5. When declaring a variable, you can assign a value or do not assign a value.
6. The difference between a constant and a read-only variable:
A. Constants must be initialized at declaration time, and values cannot be modified after they have been specified. Read-only fields can be initialized at declaration time, or they can be specified in constructors, and values cannot be modified after construction.
B. Constants are static, and read-only fields can be static and dynamic, so you can no longer use static modifiers
C.const can be used in fields and local variables, readonly can only be decorated with fields
C # constants and variables, and their scope and naming conventions