VB.net's variable

Source: Internet
Author: User
Tags abs error handling integer variables range valid

A value is temporarily stored with a variable while Visual Basic executes the application. A variable has a name (a word used to refer to the value contained in a variable) and a data type (determines the kind of data that a variable can store). You can think of a variable as the place where the unknown value resides in memory. For example, suppose that a program for selling apples is being laid out for the fruit. Apple's price and sales were not known until the sale actually took place. At this point, you can design two variables to hold the unknowns and name them "Appleprice" and "ApplesSold". Each time the program is run, the user provides a specific value for the two variables. In order to calculate the total sales and display the results in a text box called "TxtSales", the code should be like this:
Txtsales.txt=appleprice*applessold
This expression returns a different amount each time, based on the value provided by the user. Because you have a variable, you can design an equation without having to know what the actual input is. In this example, the "Appleprice" data type is decimal and the "applessold" data type is an integer. Variables can also represent many other values, such as storing text values, dates, various numeric types, and even objects.

1. Storing and retrieving data in a variable
Evaluates with an assignment statement and assigns the result to a variable:
Applessold=10 ' passes the value 10 to the variable
Applessold=applessold+1 ' variable value increased by one
Note: The equal sign in the example is an assignment, not equal to an operator, which assigns a value of 10 to the variable applessold.

2. Declaring variables
Declaring a variable is to notify the program beforehand of the variable. To declare a variable with a "dim" statement, the "Dim" statement provides the variable name:
Dim Variablename as Type
Variables declared within a procedure with a "Dim" statement exist only if the procedure is executed. As soon as the process is finished, the memory space in which the variable is stored is released. In addition, the value of a variable in a procedure is local to a procedure, that is, a variable in another procedure cannot be accessed in one procedure. Because of these characteristics, you can use the same variable names in different procedures without worrying about conflicts and errors at compile time.

Variable names have the following naming principles:
• Must begin with a letter
• cannot contain embedded (English) periods or embedded type declaration characters
• No more than 255 characters
• Must be unique within the same range

A range is a field that can refer to a variable, such as a procedure, a function, and so on. Because of the optional "as Type" clause in the "Dim" statement, you can define the data type or object type of the variable being declared. The data type defines the type of information that the variable stores. Variables can also contain objects from Visual Basic or other applications, such as "Form" and "TextBox".

Note: "As Type" is required by default, if you want to turn "as type" to optional, set the "Option Strict" in the build option in the Project property page to "off" so that in a variable declaration without "as type", " Object type is its default data type.

(1). Implicit declaration
The "Option Strict" setting in the Build option in the Project property page is set to "off", and a trap declaration is allowed in the project, that is, the variable must not be declared before a variable is used. For example, you can write a function in which you do not have to declare it before using the variable tempval:
Function SAFESQR (num)
Tempval=abs (num)
SAFESQR=SQR (TempVal)
End Function
Visual Basic uses this name to automatically create a variable that, when used, can be considered declared. Although this method is convenient, if the variable name misspelled, it will cause a difficult to find error. For example, suppose this function is written as:
Function SAFESQR (num)
Tempval=abs (num)
SAFESQR=SQR (TemVal)
End Function
It looks like the two pieces of code seem to be the same. But because the "tempval" variable name is incorrectly written in the penultimate line, the function always returns 0. When Visual Basic encounters a new name, it does not distinguish the variable name from being written incorrectly, and then creates a new variable with that name.
(2). Explicit declaration
To avoid trouble with the wrong variable name, Visual basic emits an error warning whenever you encounter a name that is not explicitly declared as a variable. To explicitly declare, simply set option Explicit in the "Build" options in the Project property page to "on". If you execute the statement on a form or standard module that contains a "SAFESQR" function, Visual Basic determines that both "TempVal" and "temval" are undeclared variables and send an error message for both. You can then explicitly declare "TempVal":
Function SAFESQR (num)
Dim TempVal
Tempval=abs (num)
SAFESQR=SQR (TempVal)
End Function
Because Visual Basic displays an error message to the misspelled "TemVal", you can immediately understand what the problem is. Because option Explicit helps to compile system error handling, it is generally set to "on" before writing code.

3. Understanding the scope of variables
The scope of the variable determines the part of the code that can access the variable. When declaring a variable inside a procedure, only the code within the procedure can access or change the value of that variable; it has a scope that is local to the process. However, there are times when you need to use a variable with a larger scope, such as a variable whose value is valid for all processes within the same module, even for all processes in the entire application. Visual Basic allows you to specify its scope when declaring a variable.

4. Variables used within the process
Process-level variables are recognized only in the process of declaring them, and they are referred to as local variables. Use the "Dim" keyword to declare them, for example:
Dim IntTemp as Integer
Variables declared with "Dim" exist only during the execution of a procedure while the entire application is running. Local variables are the best choice for any temporary calculation. For example, you can establish more than 10 different procedures, each containing a variable called "intTemp." As long as each "intTemp" is declared as a local variable, each procedure only recognizes its own version of "IntTemp". Any process can change the value of its own local "intTemp" variable, without affecting the "intTemp" variable in the other process.

5. Variables used inside the module
By default, module-level variables are available to all procedures for the module, but the code for other modules is unavailable. Module-level variables can be established at the declaration segment at the top of the module using the Private keyword to declare the module-class variable. For example:
Private intTemp As Integer
At the module level, there is no difference between "private" and "Dim," but "private" is better because it is easy to differentiate it from "public" and make it easier for the code to understand.

Variables used by all modules
To make module-level variables valid in other modules, declare variables with the "public" keyword. The values in a public variable can be used in all procedures of the application. As with all module-level variables, public variables are declared at the declaration segment at the top of the module, for example:
Public IntTemp as Integer
Note: Public variables cannot be declared in a procedure, but public variables can only be declared in the module's declaration segment.

6. Static variables
Variables have periods of their existence, during which the variables can hold their value. The values of module-level and public variables are maintained throughout the lifetime of the application. However, for local variables declared by Dim and procedures for declaring local variables, these local variables exist only if the procedure is executing. Typically, when a procedure is executed, the value of its local variable is no longer present, and the memory occupied by the variable is freed. When the procedure is executed the next time, all its local variables are reinitialized. However, you can define a local variable declaration as static, thus preserving the value of the variable. Declare one or more variables within a procedure using the "Shared" keyword exactly the same as the "Dim" statement:
Shared Depth
For example, the following function adds the previous operating value stored in the static variable "accumulate" to a new value to calculate the total value of the operation.

Function runningtotal (num)
Shared ApplesSold as Integer
Applessold=applessold+num
Runningtotal=applessold
End Function
If you declare "ApplesSold" with "Dim" instead of "Shared", the previous cumulative value is not preserved by calling the function, and the function simply returns the same value that called it. The same effect is achieved by declaring "ApplesSold" in the module's declaration segment and making it a module-level variable. However, once this method changes the scope of the variable, the process is no longer exclusive access to the variable. Because other processes can also access and change the values of variables, the total value of the operation may be unreliable and the code will be more difficult to maintain.

Note: The previous version of Visual Basic uses the "static" keyword to declare variables, and in vb.net the "Shared" keyword replaces the "static" keyword, and static variables are used with caution, because once a static variable is declared, the variable resides in memory. If you declare a large number of static variables, it is possible to affect the performance of the system.

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.