Unit 2 Variable:: Navin Malla Birendranagar 11 Airport Surkhet
Unit 2 Variable:: Navin Malla Birendranagar 11 Airport Surkhet
Unit 2 Variable:: Navin Malla Birendranagar 11 Airport Surkhet
Variable:
A variable is an identifier that denotes a storage area in the memory. For example
you can use a variable to store values, such as 3, 3.4, or Hello World. Every variable
has a type, which determines the values that can be store in to. A variable can store
different values during the execution of a program. Some examples of meaningful
variable names are salary, height, name, age and total_marks.
You should remember the following points while assigning a name to a variable in
Visual Basic 2010
A variable name can only contain alphabets, digit or numeric value.
A variable name should not begin with a digit or numeric value.
A variable name cannot contain a blank space.
Keywords cannot be used as variable names.
Declaring variables:
Variables are the names of the storage location. A variable can be used to store a
value of any data type. In Visual Basic 2010, by default, you must declare all
variables before using them. You can do that by using the Dim statement. Dim
statement is used to declare the data type of any variable in Visual Basic program
The general form of declaration of a variable is:
Dim variable1, variable2,,variableN As [New][ Type]
Some sample valid variable declarations are:
Dim Name, Address As String
Dim RollNo As Integer
A variable can be assigned a value at the time of its declared by using the = sign, as
shown in the following code snippet:
Dim Name As String="Rajendra"
Dim RollNo As Integer=1
Dim Grade As Char="A"
Variable names can be prefixed with string to indicate their data type. The use of
variable prefixes is optional. A list of some of the prefixed that have become
conventional for predefined data types in Visual Basic 2010 is given in table.
Table: Variable Prefixes
Data Type
Prefix
Boolean
Bin
Byte
Byt
Date
Dt
Double
Dbl
Error
Err
Integer
Int
Long
Lng
Object
Obj
Single
Sng
String
Str
Types of Variables
Youve learned how to declare variables and that all variables should have a type.
But what data types are available? Visual Basic recognizes the following five
categories of variables:
Numeric
String
Boolean
Date
Object
The two major variable categories are numeric and string. Numeric variables store
numbers, and string variables store text. Object variables can store any type of data.
Numeric Variables
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]
Youd expect that programming languages would use the same data type for
numbers. After all, a number is a number. But this could`nt be further from the
truth. All programming languages provide a variety of numeric data types, including
the following:
Integer (there are several Integer data types)
Decimal
Single (floating-point numbers with limited precision)
Double (floating-point numbers with extreme precision)
Integer Variables
There are three types of variables for storing integers, and they differ only in the
range of numbers each can represent. As you understand, the more bytes a type
takes, the larger values it can hold. The type of Integer variable youll use depends
on the task at hand.
String Variables
The String data type stores only text, and string variables are declared as follows:
Dim some Text As String
You can assign any text to the variable some Text. You can store nearly 2 GB of text
in a string variable (thats 2 billion characters, and its much more text than you care
to read on a computer screen). The following assignments are all valid:
Dim a String As String
A String = Now is the time for all good men to come to the aid of their country a
String =
A String = There are approximately 25,000 words in this chapter
A String = 25,000
Character Variables
Character variables store a single Unicode character in two bytes. In effect,
characters are Unsigned Short integers (UInt16), but the Framework provides all the
tools you need to work with characters without having to resort to their numeric
values (a very common practice for the older among us).
To declare a Character variable, use the Char data type:
Dim char1, char2 As Char
You can initialize a Char variable by assigning either a character or a string to it. In
the letter case, only the first character of the string is assigned to the variable. The
following statements will print the characters a and A to the Output window:
Dim char1 As Char = a, char2 As Char =ABC
Constant:
Constants are the names given to the values that do not change during the execution
of a program. A Constant is declared with the Const keyword, as shown in the
following code snippet.
Const pi=3.14159
In the preceding code snippet, we have created a constant, named Pi, with the value
3.14159.
eg:
Module Module1
Sub Main()
Const Pi = 3.14159
Dim Radius, Area As Single
Radius = 2
Area = Pi * Radius * Radius
Console.WriteLine("Area = " & Str(Area))
Console.ReadLine()
End Sub
End Module
Forcing variable declaration
undeclared variables name appears in your code, the editor will underline the
variables name with a wiggly line, indicating that it caught an error. The
description of the error will appear in the Task List window below the code window.
If you rest the cursor over the segment in question, you will see the description of
the error in a ToolTip box. To change the default behavior, you must insert the
following statement at the beginning of the file:
The Strict, and Explicit
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]
The Visual Basic compiler provides three options that determine how it handles
variables:
The Explicit option indicates whether you will declare all variables.
The Strict option indicates whether all variables will be of a specific type.
Option Explicit Off
The Option Explicit statement must appear at the very beginning of the file. This
setting affects the code in the current module, not in all files of your project or
solution. You can turn on the Strict (as well as the Explicit) option for an entire
solution. Open the projects properties page (right-click the projects name in
Solution Explorer and select Properties), select the Compile tab, and set the Strict
and Explicit options accordingly,
Option Explicit Off
Public Class Form1
Public Const s As Integer = 100
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
var1 = "Thank you for using Fabulous Software"
var2 = 49.99
MsgBox("variable is " & var1.GetType().ToString())
MsgBox("variable is " & var2.GetType().ToString())
End Sub
End Class
Option Explicit Off
Option Strict Off ' allow to mix different datatype
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]
Data Type
A data type determines the type of data that is stored in a variable. The below table
lists all the data types supported by Visual Basic 2010, along with the storage size
and range of values of these data types:
Table: Visual Basic 2010 Data Types
Data Type
Storage Size
Value Range
Boolean
Depends on the
implementing platform
True or False
Byte
1 byte
0 through 255
Char (single
Character)
2 bytes
0 through 65535
Date
8 bytes
0:00:00(midnight) on Jan
1,0001 through 11:59:59 PM
on December 31, 9999
Decimal
16 bytes
(+/-7.9E+28)
(+/-1E-28)
-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,684 through
2,147,483,647.
Long (long
integer)
8 bytes
-9223,372,036,854,775,808
through
9223,372,036,854,775,807
(9.2E+18)
Object
4 bytes on 32-bit
platform
SByte
1 byte
Short(short
integer)
2 byte
-3,4028235E+38 through
-1.401298E-45 for negative
values;
1.401298E-45 through
3.4028235E+38 for positive
values;
String (variablelength)
Depends on
implementing platform
0 to approximately 2 billion
Unicode characters.
UInteger
4 bytes
0 through 4,294,967,295.
ULong
8 bytes
O through
18,446,744,073,709,551,615
(1.8E + 19).
UShort
2 bytes
0 through 65,535.
While working with data type in visual Basic, sometimes you need to convert the
data type for a value stored in a variable to another data type. Converting one data
type to another type is known as data type conversion. Before performing data type
conversion between two data types, you must ensure that these data types are
compatible to one another.
Visual Basic 2010 provides a number of conversion function to perform data type
conversions. Given table lists data type conversion available in Visual Basic 2010,
along with their purpose.
Table: Data Type Conversion Functions in Visual
Basic 2010
Conversion
Function
Purpose
CBool
CByte
CChar
CDate
CDbl
CDec
CInt
CLng
CObj
CShort
CSng
CStr
CUInt
CULng
CUShort
Module Module1
Sub Main()
Dim dblData As Double
Dim intData As Integer
Dim boldata As Boolean
Dim lngdata As Long
dblData = 3.14159
intData = CInt(dblData)
boldata = CBool(intData)
lngdata = CLng(boldata)
Console.WriteLine("intData = " & Str(intData))
Console.WriteLine("bolData = " & Str(boldata))
Console.WriteLine("lngData = " & Str(lngdata))
Console.ReadLine()
End Sub
End Module
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]
If you cannot remember the name of a particular conversion function, you can also
us the CType function, which allows you to specify a type you want to convert to.
Listing code shows the code for converting data types by using the CType function.
Module Module1
Sub Main()
Dim dblData As Double
Dim intData As Integer
dblData = 3.14159
intData = CType(dblData, Integer)
Console.WriteLine("intData = " & Str(intData))
Console.ReadLine()
End Sub
End Module
More often than not the CType function generates a compilation error if the
conversion between the data types of the provided parameter is not possible. Even
the lack of a compiler error does not guarantee a successful conversion. In case you
are not properly working. In such cases, in Visual Basic 2010 uses TryCast
function that works similar to the CType function. The only difference is that
instead of throwing an exception, it returns Nothing in the event of the failure.
Code for using the TryCast Function
Module Module1
Sub Main()
Dim dblData As Object
Dim strData As String
dblData = 3.14159
strData = TryCast(dblData, String)
If strData IsNot Nothing Then
Console.WriteLine("intData=" & Str(strData))
End If
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]
Operation
Description
Example
Result
Addition
5+5
10
Subtraction
10-5
Multiplication
8*4
32
Division
10/5
Integer
5\2
division
Exponentiatio
n
Mod
Modulus
7 mod 5
2. Assignment Operators:
An assignment operator is an operator that stores the result of an operation in
a variable on the left side of the operator. Table 1.2 lists the different
assignment operators available in Visual Basic 2010.
Table 1.2 Assignment Operators in Visual Basic 2010
Operator
Operation
=
Assign a value to a variable or property
(Assignment
)
^=
*=
/=
\=
+=
-=
&=
<< =
variable
>> =
eg:
a+=b or
a=a+b
3. Concatenation Operators:
The process of combining two text strings into one string is called
concatenation and the operators used to perform string concatenation are
called concatenation operators. Table 1.3 lists the different concatenation
operators available in Visual Basic 2010:
Table 1.3 Concatenation Operators in Visual Basic 2010
Operato Description
r
Example
Result
&
Concatenates two
strings
Visual Basic
2010
Concatenates two
strings
Visual Basic
2010
4. Comparison Operators:
Comparison operators are used to compare two expressions. You can use then
operators to compare numeric values, strings, and objects. A comparison
operation returns a Boolean value, either True or False, as a result. Table 1.4
lists the different comparison operators available in Visual Basic 2010:
Table 1.4 Comparison Operators in Visual Basic 2010
Operator
Description
= (Equal to)
Example
24-30
False
Is
IsNot
Like
Logical operators are those operator that are used with expressions and
produce a Boolean value. Visual Basic 2010 supports six logical operators:
Not, And, Or, Xor, AndAlso and OrElse. Table 1.5 lists the different logical
and bitwise operators available in Visual Basic 2010:
Table 1.5 Logical and Bitwise Operators in Visual Basic 2010
Operato
r
Description
Example
And
Not
Or
Xor
AndAlso
OrElse
6. Miscellaneous Operators:
In addition to all operators discussed so far, some other operators are also used
in Visual Basic 2010, called miscellaneous operators. There are five
miscellaneous operators in Visual Basic 2010: AddressOf, GetType, TypeOf,
Function. Table 1.6 lists the different miscellaneous operators available in
Visual Basic 2010:
Table 1.6 Miscellaneous Operators in Visual Basic 2010
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]
Operator
Description
AddressOf
GetType
Function
expression
If
TypeOf
Array:
An array is a set of values that are logically related to each other, such as marks
obtained by the students of a class in a particular subject. It enables you to stores a
set of the same data type.
An array allows you to refer to these related values by the same name and to use a
number, called index, to identify individual values. The individual values of an
array are called the elements of the array. These elements are stored in the array
with the index values starting from 0 to one less than the size of the array.
Array Declaration:
An array, like any other variables, must be declared with the Dim statement
followed by the name of the array.
for example:
Dim Name(15)
Dim Salary(15)
Dim Names(10,20)
Optionally, you could specify the type of the array's elements with the As keyword:
Dim Name(15) As String
Dim Salary(15) As Long
Dim Names(10,20) As String
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]
Dynamic Array:
Dynamic arrays are the arrays whose size varies at runtime. This type of array is
used to store a list of values that can be changed during the execution of program.
You can declare a dynamic array without specifying size in the parenthesis, by
using the Dim statement. To specify the size of the array at runtime, you need to use
the ReDim statement, as shown in the following code snipped:
ReDim [Preserve] varname (subscripts)
In the preceding syntax, the Preserve keyword is used to preserve the data an
existing array when you change the size of the last dimention. The varname
argument holds the name of the array to dimension again.
Consider the following code snippet,
Dim DynaArr( ) As String
ReDim DynaArr(10)
DynaArr(0)="String10"
'Need more data space !
ReDim DynaArr(100)
DynaArr(50)="String 50"
Module Module1
Sub Main()
Dim counter As Integer
Dim studentName() As String
ReDim studentName(3)
Console.WriteLine("Enter the Student Names")
For counter = 0 To 2
Console.Write("Student " & (counter + 1) & " : ")
studentName(counter) = Console.ReadLine()
Next counter
ReDim Preserve studentName(5)
For counter = 3 To 4
Console.Write("Student " & (counter + 1) & " : ")
studentName(counter) = Console.ReadLine()
Next counter
Console.WriteLine("The Student Names are:")
For counter = 0 To 4
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]
Console.WriteLine(studentName(counter))
Next counter
Console.Write("press ENTER to exit...")
Console.ReadLine()
End Sub
End Module
Enumeration
Enumerations or Enums are strongly typed constants. They are essentially unique
types that allow you to assign symbolic names to integral values. Enumerations can
be declared using the Enum keyword at the module, class, structure, procedure.
You can use enumerations to define a set of values that are logically related to each
other.
eg:
Module Module1
Enum Days
Sunday = 1
Monday = 2
Tuesday = 3
Wednesday = 4
Thursday = 5
Friday = 6
Saturday = 7
End Enum
Sub Main()
Console.WriteLine("Wednesday is day " & Days.Wednesday)
Console.ReadLine()
End Sub
End Module
Strings:
A string is a sequence of character. Strings are supported by the .NET String class
in Visual Basic. You declare a string in the following way:
Dim strvar As String
Similar to other types of variables, you can also initialize a string when you declare
it, as shown in the following code snippet:
Dim strvar As String = "Rapti Engineering College"
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]
Commonly used string handling functions and methods are given in the table.
Table: String Handling Functions and Methods in Visual Basic 2010
Functions & Methods
Operation
Convert string
=, String.Copy
Copying strings.
String.Split
Len, String.Length
Mid, String.SubString
Get a substring
String.Insert
Insert a substring
LSet,Rset,String.PadLeft, String.PadRight
Remove text
Mid,String.Replace
Replace text
Option Compare
Search Strings
String
eg:
Imports System.Console
Imports Stg = Microsoft.VisualBasic.Strings
Module Module1
Sub Main()
MsgBox(Stg.Right("Hello World", 5))
ReadLine()
End Sub
End Module
This example uses the UCase, LCase, Len,Trim and Mid functions.
Module Module1
Sub Main()
Dim strText1 As String = "rapti engineeing college"
Dim strText2, strText3, strText4, strText5 As String
Dim strText6, strText7 As String
strText2 = UCase(strText1) 'change in uppercase
strText3 = strText1.ToUpper 'change in uppercase
strText4 = strText2.ToLower 'change in lowercase
strText5 = LCase(strText2) 'change in lowercase
strText6 = Len(strText1) 'finding length of strings
strText7 = strText1.Length 'finding length of strings
' Initializes string.
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]
Console.WriteLine(nw)
Console.ReadLine()
End Sub
End Module
Example 2:
Module Module1
Sub Main()
Dim TestDateTime As Date = #1/27/2001 5:04:23 PM#
Dim TestStr As String
' Returns current system time in the system-defined long time
format.
TestStr = Format(Now(), "Long Time")
Console.WriteLine(TestStr)
' Returns current system date in the system-defined long date
format.
Dim TestStr1 = Format(Now(), "Long Date")
Console.WriteLine(TestStr1)
' Also returns current system date in the system-defined long
date
' format, using the single letter code for the format.
Dim TestStr2 = Format(Now(), "D")
Console.WriteLine(TestStr2)
' Returns the value of TestDateTime in user-defined date/time
formats.
' Returns "5:4:23".
Dim TestStr3 = Format(TestDateTime, "h:m:s")
Console.WriteLine(TestStr3)
' Returns "05:04:23 PM".
Dim TestStr4 = Format(TestDateTime, "hh:mm:ss tt")
Console.WriteLine(TestStr4)
' Returns "Saturday, Jan 27 2001".
Dim TestStr5 = Format(TestDateTime, "dddd, MMM d yyyy")
Console.WriteLine(TestStr5)
' Returns "17:04:23".
Dim TestStr6 = Format(TestDateTime, "HH:mm:ss")
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]
Console.WriteLine(TestStr6)
' Returns "23".
Dim TestStr7 = Format(23)
Console.WriteLine(TestStr7)
' User-defined numeric formats.
' Returns "5,459.40".
Dim TestStr8 = Format(5459.4, "##,##0.00")
Console.WriteLine(TestStr8)
' Returns "334.90".
Dim TestStr9 = Format(334.9, "###0.00")
Console.WriteLine(TestStr9)
' Returns "500.00%".
Dim TestStr10 = Format(5, "0.00%")
Console.WriteLine(TestStr10)
Console.ReadLine()
End Sub
End Module