C # the compiler has compiled SS into a string variable. After the SS is output, enter ". the corresponding methods and attributes of the string type variables are also listed. Therefore, we can conclude that C # regards ss as the string type rather than the object. Therefore, using VAR to define variables can also have the advantages of objects and strong types. In C #3.0, a new way of declaring variables is provided. This is var. With this keyword, you do not need to specify the type when declaring a variable. The variable type is determined by the compiler during initialization.
I. use VaR to define variables
In C #3.0, a new way of declaring variables is provided. This is var. With this keyword, you do not need to specify the type when declaring a variable. The variable type is determined by the compiler during initialization.CodeAs follows:
Varss = "ABCD ";
MessageBox. Show (ss. GetType (). tostring ());
The above code will show system. string, which proves that we should not regard VaR as JavaScript var. The difference between them is that JavaScript is a weak language and variables in JavaScript (including variables declared with VAR) you can change the type, as shown in the following JavaScript code:
Vars = "ABCD ";
S = 3;
Alert (s );
The above code assigned a string to S for the first time, and the second line of code assigned an integer. Such code has no problems in JavaScript. But in C #3.0, once the VaR variable is initialized, the type cannot be changed after it is determined. The following code cannot be compiled:
Varss = "ABCD ";
Ss = 44;
To sum up, using VAR to define variables has the following four features:
1. It must be initialized during definition. That is, it must be in the form of VaR S = "ABCD" instead of the following:
Vars;
S = "ABCD ";
2. Once Initialization is complete, the variable cannot be assigned a value of a different type than the initialization value.
3. var must be a local variable.
4. Using VaR to define variables is different from object. It is the same in efficiency as defining variables using a strong type. However, I suggest you declare variables in a strongly typed manner if you know the type of the variables in advance. Otherwise, a large amount of VaR will be used, making it difficult for developers to determine the type of a variable. This is not conduciveProgram.