0% found this document useful (0 votes)
7 views

VB Data Types and Naming Conventions

Uploaded by

naazarhama11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

VB Data Types and Naming Conventions

Uploaded by

naazarhama11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Data Types and Naming Conventions

A variable is simply a name you give to an area of memory in which a data value used by
your program is stored. When you need to retrieve that data, or modify its value, you can
refer to the memory location by the variable's name.
The VB variable types, as well as the range or types of values they can store, are listed
below. The lists are broken out between numeric types (integer and float) and non-numeric
types.
Numeric Types
• Integer Types: These are used to represent integer (whole) numbers. The .NET
Framework provides a variety of integer types:
Variable System Type Size Range
Type Name
Byte System.Byte 1-byte unsigned integer 0 to 255
Short System.Int16 2-bytes signed integer -32768 to 32767
Integer System.Int32 4-bytes signed integer -231 to 231-1
Long System.Int64 8-bytes signed integer -263 to 263-1
SByte System.SByte 1-byte signed integer -128 to 127
UShort System.UInt16 2-bytes unsigned integer 0 to 65535
UInteger System.UInt32 4-bytes unsigned integer 0 to 232-1
ULong System.UInt64 8-bytes unsigned integer 0 to 264-1
• Floating Types
These are used to represent real numbers (numbers that can have a decimal portion).
There are three floating types in the .NET Framework:
VB System Type Size No. of digits Range (approximate)
Variable Name
Type
Single System.Single 4 7 significant digits +/- 1.4 x 10-45 to +/- 3.4 x
bytes 1038
Double System.Double 8 15-16 significant +/- 5.0 x 10-324 to +/- 1.7 x
bytes digits 10308
Decimal System.Decimal 16 28 significant digits +/- 1.0 x 10-28 to +/- 7.9 x
bytes 1028
The Decimal data type is often used to store currency values.
Non-Numeric Types
Variable System Type Name Size Range
Type
Char System.Char 2 bytes Unicode One character
character
String System.String 10 + 2 bytes per Up to 2 billion characters
character
Object System.Object 4 bytes A "supertype" of all types in the
.NET Framework.It can contain
any type.
Boolean System.Boolean 2 bytes True or False
Date System.DateTime 8 bytes 0:00:00 (midnight) on January 1,
0001 through 11:59:59 PM on
December 31, 9999

The rules for forming a valid VB variable name are as follows:


(1) The first character must be a letter A through Z (uppercase or lowercase letters may
be used). Succeeding characters can be letters, digits, or the underscore (_) character (no
spaces or other characters allowed).
(2) The final character can be a "type-declaration character". Only some of the variable
types can use them, as shown below:
Data Type Type Declaration Character
String $
Integer %
Long &
Single !
Double #
Decimal @
Use of type-declaration characters in VB is very “old school”, dating back to the days of
BASIC (not Visual Basic or “classic” Visual Basic, but BASIC). The preferred style
is to use the "As" clause in a data declaration statement. For example, use Dim
strMyData As String instead of Dim strMyData$.
(3) The name can contain a maximum of 255 characters.
(4) The name cannot be a reserved word (VB keyword).
VB is not case-sensitive: PAY, Pay and pay all refer to the same variable. If you type a
variable on a line in a case other than the case you used when you declared the variable, VB
will change the case to match that of the declared variable when you leave that line.
Variable Naming Conventions
As long as you stick to the rules above, VB .NET is "happy"; however, many programmers
follow stylistic naming conventions in an effort to improve the readability of their code.
Naming conventions involve using a one-to-four character lower-case prefix to start off the
name. The purpose of the prefix is to identify the data type of the variable (like "int" for
integers and "str" for strings). These naming conventions are sometimes called "Hungarian
naming conventions" (after Charles Simonyi, an early Microsoft programmer – and
Hungarian native – who proposed the conventions). Two other prominent programmers,
Leszynski and Reddick, also have led the charge for naming conventions.
It should be noted that the use of Hungarian naming conventions is the subject of much
debate. Some programmers are “fans” of it, others feel it is completely and utterly ridiculous
and use alternate naming conventions or none at all. My preference is to use the naming
conventions discussed below, and these are used in the sample programs provided here. Of
course, you can do your own research, and come up with the method that works for you.
The chart below shows commonly used variable types, a recommended three-character
prefix, and a sample variable name:
Variable Type Recommended Prefix Sample Variable Name
Boolean bln blnDataIsValid
Date dtm (for "Date/Time") dtmEmpBirthDate
Decimal dec decBigMoney
Double dbl dblAnnSalary
Integer int intCounter
Long lng lngBigIntValue
Object obj objExcelApp
Single sng sngHrlyRate
String str strMyWord

Note the style of using a lower-case, three-character prefix, followed by a descriptive name in
mixed case. This style of naming variables found in a lot of programming documentation.
It is also recommended that you indicate the scope of the variable with an additional one-
character prefix in front of the variable name. My recommendations are:
• None for a local variable (i.e., a variable that is declared in a Sub or Function). Thus,
variable names like the ones in the sample names above would be used for local
variables.
• The letter m for module-level variables (variables that are declared with Private scope
in the General Declarations section of a code module). Such variables can be "seen"
in any Sub or Function of that module. For example, a String variable declared at the
module level might be named mstrEmpName.
• The letter g for global (project-level) variables (variables that are declared with
Public scope in the General Declarations section of a code module). Such variables
can be "seen" in any Sub or Function of any module in the project. For example, a
Boolean variable declared at the project level might be named gblnFirstTime.
• The letter p for a variable that is passed as an argument to a Sub or Function
procedure. Such a variable would have local scope within that procedure, but it is
defined within the procedure's header. For example, an Integer variable passed to a
Sub might be named pintCurrCode when defined in the Sub's header.
In addition, it is recommended that the letter a be used to indicate an array name. In an array
name, the letter "a" would appear before the variable type indicator, but after the scope
indicator. For example, an array of Boolean switches might be named as follows, depending
on where it is declared:
ablnSwitches local level
mablnSwitches module level
gablnSwitches global (project) level
pablnSwitches passed parameter

What is Scope?

The scope (or visibility) of an element in code is all the code that can refer to it without
qualifying its name. Stated other way, an element's scope is it's accessibility in code. Scope is
normally used when writing large programs as large programs divide code into different
classes, modules, etc. Also, scope prevents the chance of code referring to the wrong item.

The syntax for declaring a variable in VB is as follows:

[Dim | Private | Public | Static | Protected | Friend | Protected


Friend] variablename [As datatype]

Note that you use one of seven keywords to declare a variable; which one you use depends on
the scope you want the variable to have. Levels of scope are:
 project-level (also called "global" or "application" scope; the variable is accessible
to all procedures in all modules of the project)
 module-level (the variable is accessible to all procedures in the module in which it
is declared)
 local-level (the variable is accessible only to the procedure in which it is declared)
 block level (the element declared is available only within the code block in which
it is declared)

In addition to the keyword used to declare the variable, the location of the variable
declaration also affects its scope. A variable may be declared in one of two places:

· The General Declarations Section of a form or standard module. This section of a


module is not labeled as such; it simply exists at the beginning of a code module, after the
"Option Explicit" statement but prior to the first Sub or Function procedure. Declaring a
variable here makes it a project-level variable (if the Public keyword is used) or a
module-level variable (if the Private or Dim keyword is used).

· Within a Sub or Function procedure. Declaring a variable here makes it a local-level


variable; only the Dim or Static keyword can be used here. The recommended practice is
to declare all local variables within a procedure immediately following the Sub or
Function header and prior to any executable statements (although VB will allow you to
declare variables anywhere within the procedure).

What is Accessibility?
Accessibility means the permission for code to read or write to an element. In other words,
it’s the restriction to access the element (variable or subroutines) which is decided by you
using the keywords mentioned above, these keywords are also known as Access Modifiers.
The table below shows the access modifiers in detail:
Access Affect on Elements
Modifier
Public Can be accessed from anywhere.
Private Can be accessed only by members within the type that defines it.
Friend Can be accessed from all types within the assembly, but not from outside the
assembly.
Protected Can be accessed only by members within the type that defines it or types that
inherit from that type.
Protected Can be accessed from all types within the assembly or from types inheriting
Friend from the owning type. This is the union of Protected (protected)
and Friend (internal) access.

The following table shows how the seven different declarative keywords and the location of
their declaration affects the scope:
Keyword Where
Used to Declared
General Declarations General Sub or Function
Declare the à Section of a Form Declarations procedure of a
Variable: (.frm) Module Section of a Form or
$ Standard (.bas) Standard Module
Module
Dim (preferred keyword module-level scope module-level local-level scope
for local-, but not scope (value of the
module-level variables) variable is NOT
preserved between
calls
Static not allowed not allowed local-level scope
(value of the
variable is
preserved between
calls)
Private (preferred module-level scope module-level not allowed
keyword for module- scope
level variables)
project-level scope
(but references to the
Public project-level scope not allowed
variable must be
qualified with the
form name; also there
are some minor
restrictions on the
types of variables that
can be declared as
public in a form)
Protected Module- level scope Module-level not allowed
scope
Friend (This is only
allowed in classes not in
Assembly level scope not allowed not allowed
standard modules)
Protected Friend (This
is only allowed in classes
Assembly level scope not allowed not allowed
not in standard modules)

If the "As datatype" clause is omitted in a variable declaration, the variable type defaults
to Object, unless a type declaration character is used. (Note: In previous versions of VB, the
default data type was Variant, which does not exist in VB.NET.)
The following two statements both declare an integer called "intCounter" (the "As" version
is preferred):
Dim intCounter As Integer
Dim intCounter%
The following two statements both declare an Object variable called "objWhatever":
Dim objWhatever As Object
Dim objWhatever
In VB .NET the String variables can be only of variable-length, and not fixed-length (as was
allowed in VB6 and earlier). The difference in declaring them is shown below:
'Variable-length string, length changes depending upon length of whatever is
assigned to it:
Dim strPlayerName As String
'Fixed-length string, always 2 bytes (legal in VB6 and earlier, illegal in VB.NET)
Dim strStateAbbrev As String * 2 ' ILLEGAL IN VB.NET
Note: Protected, Friend, or Protected Friend will not be used in the sample applications
presented here.
Static Variables
The Static keyword is rarely used. It allows a local variable to retain its value after it goes
out of scope.
Suppose you have a Sub in a form called CountThem that looks like this:
Private Sub CountThem()
Dim intI As Integer
Static intJ As Integer
intI = intI + 1
intJ = intJ + 1
Debug.Print("intI = " & intI & ", intJ = " & intJ)
End Sub

Suppose you have some other Sub that calls CountThem three times in a row:
Call CountThem
Call CountThem
Call CountThem
The following output from Debug.Print would be as follows:
intI = 1, intJ = 1
intI = 1, intJ = 2
intI = 1, intJ = 3
Note that the "regular" variable, intI, declared with "Dim", does not retain its value between
calls, whereas the Static variable, intJ, does. Rather than use “Static”, it would be preferred to
declare “intJ” at the module- or form-level (i.e. outside of all the Sub and Function
procedures, with the keyword “Private” or “Dim”).
Note: In VB6, the keyword "Static" can also be used in the Sub procedure header, which
causes all variables in that procedure to be static. This option is no longer available in
VB.NET (i.e., the static modifier is not a valid modifier for procedure).
Multiple Declarations on One Line
VB .NET allows you to declare any number of variables on one line – you don’t need to
explicitly provide the data type of each variable, For example:
Dim intA, intB, intC As Integer
The above statement declares intA and intB and intC as Integer type values.
I recommend declaring only one variable per line.
Initialization of Variables

Variables can be declared and initialized in Visual Basic .NET on a single line. Thus you may
write:

Dim strVar As String = "This is a string."


The above statement declares a String variable and initializes its value to “This is a string”.
Similarly, you can declare and initialize more than one variable on a single line:
Dim intX As Integer = 6, intY As Integer = 9
However, each variable does have a default initialization value. Numeric variable types are
initialized to zero, Strings are initialized to "", Booleans are initialized to False, etc.
The Strict and Explicit options
The default behavior of VB.NET is to throw an exception if you attempt to use a variable
that hasn’t been declared previously. If an undeclared variable’s name appears in your code,
the editor will underline the variable’s name with a wiggly red line indicating that it caught
an error. Rest the mouse pointer on that line to see the description of the error. This means
that Option Explicit is on – that is the default setting, and you should keep it that way.
Another related option is Option Strict, which is OFF by default. Option Strict tells the
compiler whether the variables should be strictly typed or not. A strictly typed variable can
only accept values of the same type it was declared with. Some purists will advocate that this
option be turned on, however I am of the opinion that this option is too restrictive and I am
fine with leaving the default setting (off) as is.

LEGAL VS. ILLEGAL VARIABLE DECLARATIONS


The figure below attempts to highlight concepts of variable declaration and scoping
discussed previously:
PROJECT
(Form1)
Public Class Form1
'General Declarations Section …
Public intA As Integer
Private intB As Integer

Private Sub MySub1()


Dim intC As Integer
intC = intA 'OK – intA is public (declared in this form)
intC = intW 'OK – intW is public (declared in Module1)
intC = intB 'OK – intB is a module-level variable of this form
intC = intD 'Error – intD is local to MySub2
intC = intX 'Error – intX is private to Module1
End Sub

Private Sub MySub2()


Dim intD As Integer
intD = intA 'OK – intA is public (declared in this form)
intD = intW 'OK – intW is public (declared in Module1)
intD = intB 'OK – intB is a module-level variable of this form
intD = intC 'Error – intC is local to MySub1
intD = intX 'Error – intX is private to Module1
End Sub
End Class
(Module1)
Module Module1
'General Declarations Section ...
Public intW As Integer
Private intX As Integer

Public Sub MySub3()


Dim intY As Integer
intY = intA 'Error – qualification required
intY = Form1.intA 'OK – intA is public (declared in Form1)
intY = intW 'OK – intW is public (declared in this module)
intY = intX 'OK – intX is a module-level variable of this module
intY = intZ 'Error – intZ is local to MySub4
intY = intB 'Error – intB is private to Form1
intY = Form1.intB 'Ditto
End Sub

Public Sub MySub4()


Dim intZ As Integer
intZ = intA 'Error – qualification required
intZ = Form1.intA 'OK – intA is public (declared in Form1)
intZ = intW 'OK – intW is public (declared in this module)
intZ = intX 'OK – intX is a module-level variable of this module
intZ = intY 'Error – intY is local to MySub3
intZ = intB 'Error – intB is private to Form1
intZ = Form1.intB 'Ditto
End Sub
End Module

You might also like