Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Declaring variables

Declaring variables

All variables that you use must be declared somewhere within your program. The first thing the complier does is build a list of variables declared within your program. When you use a variable, the compiler looks for its name in this list. If it doesn’t find it, it gives the 'name' is not declared error.

For example, if you have a simple assignment statement:

BetPrice = 3.5

and you see the message 'BetPrice' is not declared in the error list, this is telling you that the complier does not know what BetPrice is. You must tell the compiler what BetPrice is before you use it. You do this with a declaration statement, for example:

Dim BetPrice as Decimal

The "not declared" error should now disappear.

We can combine these two statements into one:

Dim BetPrice as Decimal = 3.5

Here we declare the variable BetPrice and initialize it to 3.5 in one line. This can be handy.

You can declare several variables in one Dim statement:

Dim BetPrice As Decimal, BetSize As Decimal, TheBetId As Long

Because BetSize and BetPrice are both of type Decimal you can simplify this to:

Dim BetPrice, BetSize As Decimal, TheBetId As Long

This is same as writing:

Dim BetSize As Decimal
Dim BetPrice As Decimal
Dim TheBetId As Long

These declarations are said to be non-executable statements. They simply instruct the compiler to reserve space in memory for the variables. However, if you initialize a variable, for example:

Dim BetSize as Decimal = 2

you now have an executable statement - the value 2 is assigned at run time.


Variable access

You can use the Private, Friend or Public keywords instead of Dim for variables declared outside a sub or function:

Private BetPrice, BetSize As Decimal, TheBetId As Long

If the declared variable are to be accessed by code anywhere in your project (e.g. from another form) use Friend or Public. Use Private or Dim for variables that are only accessed by code within the current class.

Variables declared within a procedure (a procedure is a sub or function) can only be declared with Dim. These variables are local to the procedure and cannot be accessed from outside the procedure directly.

Variable access (variable scope) is a fairly large topic, This is just a brief introduction.

 

 


 


Date: 2014-12-21; view: 1008


<== previous page | next page ==>
UserState object. | Step 29. Adding controls to a form at run time.
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.006 sec.)