VB .Net

Variables, Controls and Data Types

Objectives:

Naming Controls

The most important aspect of naming a control is that its name should give a clear idea what it does. Instead of a default name such as Textbox1, give a name such as UserName to indicate what data the control holds.

The next step of naming a control is how the name would fit into the possible syntax of codes.  The goal is to help the programming codes look more like common English.  A good name not only tells the programmer what it is and does, but also makes the programming codes more like English sentences. 

Example:  Consider a program that signals room temperature.  A basic algorithm: if the room temperature is below 60°F, display a text message saying “It’s too cold!”, and if the temperature is above 85°F, display message saying “It’s too hot!”. 

Now, let’s code the algorithm:

            If roomTemp < 60 Then

                txtMessageDisplay.Text = “It’s too cold!”

            Else If

            If roomTemp > 85 Then

                txtMessageDisplay.Text = “It’s too hot!”

            End If

From the name of txtMessageDisplay, a programmer knows that it is a Text control (explained below) and it is for displaying a message.  Also it “flows” with the rest of the codes and makes more like reading an English sentence.

A better name of roomTemp variale would be sngRoomTemp to indicate that it is a single data type variable. The detail information on different types of variables are below.

When naming a control, it is recommended that you start with a three-letter prefix to identify the type of control. The following is from the MSDN.

Suggested Prefixes for Controls

Control Type Prefix Example
3D Panel pnl pnlGroup
ADO Data ado adoBiblio
Animated button ani aniMailBox
Check box chk chkReadOnly
Combo box, drop-down list box cbo cboEnglish
Command button btn btnExit
Common dialog dlg dlgFileOpen
Communications com comFax
Control (used within procedures when the specific type is unknown) ctr ctrCurrent
Data dat datBiblio
Data-bound combo box dbcbo dbcboLanguage
Data-bound grid dbgrd dbgrdQueryResult
Data-bound list box dblst dblstJobType
Data combo dbc dbcAuthor
Data grid dgd dgdTitles
Data list dbl dblPublisher
Data repeater drp drpLocation
Date picker dtp dtpPublished
Directory list box dir dirSource
Drive list box drv drvTarget
File list box fil filSource
Flat scroll bar fsb fsbMove
Form Frm FrmEntry
Frame fra fraLanguage
Gauge gau gauStatus
Graph gra graRevenue
Grid grd grdPrices
Hierarchical flexgrid flex flexOrders
Horizontal scroll bar hsb hsbVolume
Image img imgIcon
Image combo imgcbo imgcboProduct
ImageList ils ilsAllIcons
Label lbl lblHelpMessage
Lightweight check box lwchk lwchkArchive
Lightweight combo box lwcbo lwcboGerman
Lightweight command button lwcmd lwcmdRemove
Lightweight frame lwfra lwfraSaveOptions
Lightweight horizontal scroll bar lwhsb lwhsbVolume
Lightweight list box lwlst lwlstCostCenters
Lightweight option button lwopt lwoptIncomeLevel
Lightweight text box lwtxt lwoptStreet
Lightweight vertical scroll bar lwvsb lwvsbYear
Line lin linVertical
List box lst lstPolicyCodes
ListView lvw lvwHeadings
MAPI message mpm mpmSentMessage
MAPI session mps mpsSession
MCI mci mciVideo
Menu mnu mnuFileOpen
Month view mvw mvwPeriod
MS Chart ch chSalesbyRegion
MS Flex grid msg msgClients
MS Tab mst mstFirst
OLE container ole oleWorksheet
Option button opt optGender
Picture box pic picVGA
Picture clip clp clpToolbar
ProgressBar prg prgLoadFile
Remote Data rd rdTitles
RichTextBox rtf rtfReport
Shape shp shpCircle
Slider sld sldScale
Spin spn spnPages
StatusBar sta staDateTime
SysInfo sys sysMonitor
TabStrip tab tabOptions
Text box txt txtLastName
Timer tmr tmrAlarm
Toolbar tlb tlbActions
TreeView tre treOrganization
UpDown upd updDirection
Vertical scroll bar vsb vsbRate

An object’s name must start with a letter and it cannot exceed 40 characters or use spaces.  Only letters, numbers, and the underscore character can be used.

Naming Variables

Data Type

Prefix

Data Type

Prefix

Boolean

bln

Integer

int

Byte

byt

Long

lng

Collection object

col

Object

obj

Currency

cur

Single

sng

Date(time)

dtm

String

str

Double

dbl

User-def. type

udt

Error

err

Variant

vnt

Data Types and Declaring Variables and Constants

Vb .Net requires all variables to be declared before using them.

Declaring a variable means VB .Net to reserve a memory location for the value of the variable.  Using declared variables allows VB .Net to detect misspelled variable names. 

You declare a variable using the Dim statement.  Dim stands for dimension.  It is a convention to have the Dim statement at the beginning of a procedure.

Syntax of the Dim statement:

Dim variablename As datatype

Data type determines the type of data the variable can store.  By identifying the data type, VB allocates appropriate memory space.  In declaring variables, specifying data type is not mandatory.  

Data Types

The following table shows the Visual Basic .NET data types, their supporting common language runtime types, their nominal storage allocation, and their value ranges.

Visual Basic type
Nominal storage allocation
Value range
Boolean
2 bytes
True or False.
Byte
1 byte
0 through 255 (unsigned).
Char
2 bytes
0 through 65535 (unsigned).
Date
8 bytes
0:00:00 on January 1, 0001 through 11:59:59 PM on December 31, 9999.
Decimal
16 bytes
0 through +/-79,228,162,514,264,337,593,543,950,335 with no decimal point;
0 through +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest nonzero number is
+/-0.0000000000000000000000000001 (+/-1E-28).
Double
(double-precision floating-point)
8 bytes
-1.79769313486231570E+308 through
-4.94065645841246544E-324 for negative values; 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values.
Integer
4 bytes
-2,147,483,648 through 2,147,483,647.
Long
(long integer)
8 bytes
-9,223,372,036,854,775,808 through 9,223,372,036,854,775,807.
Object
4 bytes
Any type can be stored in a variable of type Object.
Short
2 bytes
-32,768 through 32,767.
Single
(single-precision floating-point)
4 bytes
-3.4028235E+38 through -1.401298E-45 for negative values; 1.401298E-45 through 3.4028235E+38 for positive values.
String
(variable-length)
Depends on implementing platform
0 to approximately 2 billion Unicode characters.
User-Defined Type
(structure)
Depends on implementing platform
Each member of the structure has a range determined by its data type and independent of the ranges of the other members.

Note   For strings containing text, use the StrConv function to convert from one text format to another.

Memory Consumption

When you declare an elementary data type, it is not safe to assume that its memory consumption is the same as its nominal storage allocation. The common language runtime assigns storage based on the characteristics of the platform on which your application is executing. In some circumstances it packs your declared elements as closely together as possible; in other cases it aligns their memory addresses to natural hardware boundaries. Also, storage assignment is different on a 64-bit platform than it is on a 32-bit platform.

The same considerations apply to each member of a composite data type such as a structure or an array. Furthermore, some composite types have additional memory requirements. For example, an array uses extra memory for the array itself and also for each dimension. On a 32-bit platform, this overhead is currently 12 bytes plus 8 bytes for each dimension. On a 64-bit platform the requirement is doubled. You cannot rely on simply adding together the nominal storage allocations of the components.