Variables and Constants
Variables and Constants
Variable
It is a named storage location in computer's memory that can contain data that can be modified during program
execution. A variables has a name, the word used to refer to the value the variable contains and a data type
(which determine the kind of data the variable can store)
Data Types
The CTS (Common Type System (CTS)) and CLS (Common Language Specification) are standards that must be
conformed to by all .NET languages
CTS defines the basic data types that IL understands. Each .Net compliant language should map its data
types to these standard data types. This makes it possible for the supported languages to communicate with
each other by passing/receiving parameters to and from each other
The Common Language Specification (CLS) works with the CTS to ensure language interoperability. It is
generally a set of minimum standards that all compilers targeting .NET must support.
Types of Data
VB provides numerous data types to allow programmers to optimize the use of computer memory. The
following table describes the various data types used in Visual Basic:
Decimal Decimal numeric values – often used to store dollars/cents. The Decimal 16
Type is almost perfect for storing (modeling) money.
Numeric Data Storage – Floating Point
Note: Strings are stored as Unicode characters in two bytes as an unsigned short (UShort). The first 127 values
store letters, digits, and special characters. The values 128 to 255 are for special characters such as keyboard
arrows while the values 256 to 65,536 are for international characters and diacritical marks
Local variables are declared with the Dim statement while module-level variables are declared with the Private
statement. When declaring variables you need to specify a variable/constant name and data type
1. Specifying an initial value for a variable is optional -- do so if necessary.
2. If an initial value is not assigned, then a string stores the "empty string" and all numeric variable types store
the value zero.
Syntax:
Dim VariableName As Type
Private VariableName As Type
Examples:
Dim StudentNameString As String
Dim AccountBalanceDecimal As Decimal = 100D
You can also declare more than one variable in a Dim statement as follows
Dim SubtotalDecimal, TotalDecimal, TaxAmountDueDecimal As Decimal
Declaring Constants
Constants are values that are stored to memory locations; however, a constant cannot have its value change
during program execution. Constants are declared with the Const statement.
Examples:
Const SALES_TAX_RATE_SINGLE As Single = 0.0725F
Const TITLE_STRING As String = "Data Entry Error"
Const MAX_SIZE_INTEGER As Integer = 4000
ii). Module level (usually use Private to declare a variable; use Const to declare a constant) – a
variable/constant can be used in any procedure on a specific form – it is not visible to other Forms.
• Use module-level variables when the values that are stored in their memory locations are used in more
than one procedure (event handlers or any other type of procedure).
• A module-level variable or constant is created (allocated memory) when a form loads into memory and
the variable or constant remains in memory until the form is unloaded.
iii). Local (use Dim/Static to declare a variable; use Const to declare a constant) – a variable/constant is
declared and used only within a single procedure.
Syntax
[Dim | Static] varname As type [=initexpr]
• The Dim keyword declares a local variable that is created when the containing procedure (sub or
function) is invoked. The variable and any value it might have is destroyed when execution of the
containing procedure ends
• The Static keyword declares a local variable that its value persist from one procedure invocation to the
next
iv). Block (use Dim to declare the variable; use Const to declare the constant) – the variable/constant is only
visible within a small portion of a procedure – Block variables/constants are rarely created.
Example1 – This example shows you how to declare numeric variables then store values to them from
Textbox controls.
'Declare variables
Dim PriceDecimal As Decimal
'Convert values from textbox controls to memory
PriceDecimal = Decimal.Parse(PriceTextBox.Text,
Globalization.NumberStyles.Currency)
Example2 – This example shows you how to declare numeric variables and store values to them from
Textbox controls using a single assignment statement in one step.
Dim QuantityInteger As Integer = Integer.Parse(QuantityTextBox.Text,
Globalization.NumberStyles.Number)
Older versions of VB used named functions to convert values. Examples are the CDec (convert to
Decimal) and CInt (convert to Integer) functions as shown below:
'Converts to decimal and Integer
PriceDecimal = CDec(PriceTextBox.Text)
QuantityInteger = CInt(QuantityTextBox.Text)
Notice that the TextBox’s Text property value of $100.00 will NOT generate an error if you use the CDec
function to convert the value as shown above—the data will convert satisfactorily. The functions are also
faster and easier to type.
Types of Conversion:
i). Implicit Conversion(Widening conversions) – this is conversion from a narrower to wider data type (less
memory to more memory) – this is done automatically as there is no danger of losing any precision. In this
example, an integer (4 bytes) is converted to a double (8 bytes):
BiggerNumberDouble = SmallerNumberInteger
ii). Explicit Conversion (Narrowing conversions) – this is also called Casting and is used to convert between
numeric data types that do not support implicit conversion.
Notice that VB uses a wider data type when calculations include unlike data types. This example produces a
decimal result.
AverageSaleDecimal = TotalSalesDecimal / CountInteger
Arithmetic Operators
It refers to operators used for mathematical calculations and are the same as in many other programming
languages. The operands might be either literal values, object properties, constants or variables
The following is a list of binary arithmetic operators.
Operator Operation
* Multiplication
/ Division
\ Integer Division
+ Addition
- Subtraction
^ Exponentiation
Mod Modulus Division
Exponentiation – This raises a number to the specified power – the result produced is data type Double.
Example: ValueCubedDouble = NumberDecimal ^ 3
Integer Division – Divide one integer by another leaving an integer result and discarding the remainder, if
any.
Example: If the variable MinutesInteger = 130, then this expression returns the value of 2 hours.
HoursInteger = MinutesInteger \ 60
Modulus Division – This returns the remainder of a division operation .Using the same value for
MinutesInteger = 500, this expression returns the value 20 minutes and can be used to calculate the amount
of overtime worked for an 8-hour work day.
MinutesInteger = MinutesInteger Mod 60
Order of Precedence
The order of precedence for expressions that have more than one operation is the same as for other
programming languages. Evaluate values and calculation symbols in this order:
(1). Values enclosed inside parentheses
(2). Exponentiation
(3). Multiplication and Division
(4). Integer Division
(5). Modulus Division
(6). Addition and Subtraction
Problem Result
X+Y^Z 66
16 / Y / X 2
X*(X+1) 6
X*X+1 5
Y^X+Z*2 22
This table shows example of mathematical notation and the equivalent VB expression.
Mathematical Notation VB Expression
2X 2*X
3(X + Y) 3 * (X + Y)
π r2 3.14 * r ^ 2
Assignment Operator
The (=) is the assignment operator. It is used store the value of the expression on the right side of the operator
to the variable on the left side of the operator. Examples:
ItemValueDecimal = QuantityInteger * PriceDecimal
HoursWorkedSingle = MinutesWorkedSingle / 60F
The updation assignment (plus symbol combined with the assignment operator) allows you to accumulate a
value in a memory variable. Examples:
TotalSalesDecimal += SaleAmountDecimal
is equivalent to statement
TotalSalesDecimal = TotalSalesDecimal + SaleAmountDecimal
Option Strict option is OFF by default in VB, and enables or disables strict type checking.
• This option is used to convert from wider data types to narrower ones (ones using less memory).
• Helps avoid the mistake of mixing data types within an expression, for example: trying to add a string
value to an integer value.
• With Option Strict Off, you can write the following assignment statement to store a value from a
textbox to a memory variable – VB will automatically convert the string data in the textbox to integer
data for storage in the variable:
QuantityInteger = QuantityTextBox.Text
Use of Option Strict On is a good practice i.e. enable strict type checking to prevent hard to find type
conversion errors. To use Option Strict On in you program, place the command after the general
comments at the top of the program as the first line of code as shown below.
'Project: ComputeApplication
'Today's Date
Option Strict On
Rounding Numbers
Use the Decimal.Round method to round decimal values to a desired number of positions to the right of the
decimal. Always specify the number of digits to round – the default is to round to the nearest whole number.
Always round when multiplying and dividing or when using exponentiation as these operations can result in
rounding errors. Simple subtraction and addition do not require rounding. Example:
SalesTaxDecimal = Decimal.Round(Convert.ToDecimal(SubtotalDecimal *
SALES_TAX_RATE_SINGLE), 2)
Example1: This shows formatting a decimal value to string for display in a textbox control – the output is
formatted as currency (dollar sign, commas, 2 decimal points – the default is to format numeric output with 2
digits to the right of the decimal point).
SalesTaxTextBox.Text = SalesTaxDecimal.ToString("C")
Example2: This shows formatting as currency, but with no digits to the right of the decimal point.
TotalDueTextBox.Text = TotalDueDecimal.ToString("C0")
Option Explicit On
Example
You are required to write a program that will enable user to calculate the sum, product, division and difference
of two numbers entered through textboxes after a click of the respective buttons. The results should be
displayed by use text box control. The program should enable the user to clear the textboxes ready for the next
input.
i) Sketch your graphical user interface assigning appropriate properties to your form and other controls
ii) Write the code for your program and declare you variables appropriately
Solution
i) Appropriate GUI with appropriate properties for the form and controls
Properties
The first two TextBox controls are used for data entry – use these names: Number1TextBox and
Number2Box
The third TextBox control is used to display the output. Set these properties:
o ReadOnly property = True,
o Name property = ResultsTextBox.
Name the buttons AddButton, SubtractButton, MultiplyButton, DivideButton, ClearButton and
ExitButton.
ii) Code
'Project: ComputeApplication
'Author name
'Today's Date
Option Explicit On
Option Strict On