Notes
Notes
1
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
.NET Framework
The .NET Framework is a managed, type-safe
environment for developing and executing
applications. The .NET Framework manages all
aspects of program execution, like, allocation of
memory for the storage of data and
instructions, granting and denying permissions
to the application, managing execution of the
application and reallocation of memory for
resources that are not needed.
The .NET Framework is designed for cross-
language compatibility. Cross-language
compatibility means, an application written in
Visual Basic .NET may reference a DLL file
written in C# (C-Sharp). A Visual Basic .NET
class might be derived from a C# class or vice
versa.
The .NET Framework consists of two main
components:
Common Language Runtime (CLR)
Class Libraries
The Common Language Runtime (CLR)
The most important concept of the .Net
Framework is the existence and functionality of
the .Net Common Language Runtime (CLR),
also called .Net Runtime for short. It is a
framework layer that resides above the OS and
handles the execution of all the .Net
applications. Our programs don't directly
communicate with the OS but go through the
CLR.
----------------------------------------------------------------------------------------------------------------------------------------------
2
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
MSIL (Microsoft Intermediate Language) Code
When we compile our .Net Program using any .Net compliant language (such as C#,
VB.Net or C++.Net) our source code does not get converted into the executable binary
code, but to an intermediate code known as MSIL which is interpreted by the Common
Language Runtime. MSIL is operating system and hardware independent code. Upon
program execution, this MSIL (intermediate code) is converted to binary executable code
(native code). Cross language relationships are possible as the MSIL code is similar for
each .Net language.
The Common Language Specification (CLS)
Earlier, we used the term '.Net Compliant Language' and stated that all the .Net compliant
languages can make use of CLR and FCL. But what makes a language a '.Net compliant'
language? The answer is the Common Language Specification (CLS). Microsoft has released
a small set of specifications that each language should meet to qualify as a .Net Compliant
Language.
The Common Type System (CTS)
.Net also defines a Common Type System (CTS). Like CLS, CTS is also a set of standards.
CTS define 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 2 languages to
communicate with each other by passing/receiving parameters to and from each other. For
example, CTS defines a type, Int32, an integral data type of 32 bits (4 bytes) which is mapped
by C# through int and VB.Net through its Integer data type.
Garbage Collection (GC)
CLR also contains the Garbage Collector (GC), which runs in a low-priority thread and checks
for un-referenced, dynamically allocated memory space. If it finds some data that is no longer
referenced by any variable/reference, it re-claims it and returns it to the OS. The presence of a
standard Garbage Collector frees the programmer from keeping track of dangling data.
----------------------------------------------------------------------------------------------------------------------------------------------
3
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Framework Class Library
The Framework Class Library (FCL) is a standard library and one of two core
components of Microsoft .NET Framework. The FCL is a collection of thousands of
reusable classes (within hundreds of namespaces), interfaces and value types.
Dot net framework contains a huge collection of reusable types (class, enumerations and
structures). These types are used for common task such as IO, Memory and Thread
management. A complete object oriented toolbox is available with Visual Studio Dot Net.
Assemblies
Assemblies are the basic unit of any application. It is a logical grouping of one or more
modules or files. Smallest unit of reuse, security, and versioning. Assemblies can be
created directly by compiler (e.g. DCCIL.exe, CSC.exe, and VBC.exe). It contains resource
data (strings, icons, etc.) and is loaded at runtime based on user locale. Assemblies can be
private or shared. It can also be stored in Global Assembly Cache (GAC)
Namespaces
A namespace is a logical container for types. It is designed to eliminate name collisions. An
assembly can contribute to multiple namespaces, multiple assemblies can contributed to a
namespace
Examples
System.Drawing
System.Windows.Forms
System.IO
System.Collections
System.Data
----------------------------------------------------------------------------------------------------------------------------------------------
4
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Data Types in VB .NET
The data type of a programming element refers to what kind of data it can hold and how that data is
stored. Data types apply to all values that can be stored in computer memory or participate in the
evaluation of an expression. Every variable, literal, constant, property, procedure argument, and
procedure return value has a data type.
Type .NET Runtime type size Range
Byte System.Byte 1 byte 0 to 255 (unsigned)
SByte System.Byte 1 byte -128 to 128 (signed)
Short System.Int16 2 bytes -32768 to 32767
UShort System.Int16 2 bytes 0 to 65535
Integer System.Int32 4 bytes -2,147,483,648 to 2,147,483,647
UInteger System.Int32 4 bytes 0 to 4294967295
Long System.Int64 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ULong System.Int64 8 bytes 0 to 18446744073709551615
Single System.Single 4 bytes
Double System.Double 8 bytes
Decimal System.Decimal 12 bytes
Char System.Char 2 bytes
String System.String (class)
Date System.DateTime 8 bytes
Boolean System.Boolean 4 bytes True or False
Object System.Object (class) 4 bytes Any type can be stored in a variable of type Object
----------------------------------------------------------------------------------------------------------------------------------------------
3
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Operators
Visual Basic comes with many built-in operators that allow us to manipulate data. An operator
performs a function on one or more operands. For example, we add two variables with the "+"
addition operator and store the result in a third variable with the "=" assignment operator like this: int
x + int y = int z. The two variables (x ,y) are called operands. There are different types of operators
in Visual Basic and they are described below in the order of their precedence.
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations that involve calculation of numeric
values. The table below summarizes them:
Operator Use
^ Exponentiation
- Negation (used to reverse the sign of the given value, exp -intValue)
* Multiplication
/ Division
\ Integer Division
Mod Modulus Arithmetic
+ Addition
- Subtraction
Concatenation Operators
Concatenation operators join multiple strings into a single string. There are two concatenation
operators, + and & as summarized below:
Comparison Operators
A comparison operator compares operands and returns a logical value based on whether the
comparison is true or not. The table below summarizes them:
Operator Use
= Equality
<> Inequality
< Less than
> Greater than
>= Greater than or equal to
<= Less than or equal to
----------------------------------------------------------------------------------------------------------------------------------------------
6
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Logical / Bitwise Operators
The logical operators compare Boolean expressions and return a Boolean result. In short, logical
operators are expressions which return a true or false result over a conditional expression. The
table below summarizes them:
Operator Use
Not Negation
And Conjunction
AndAlso Conjunction
Or Disjunction
OrElse Disjunction
Xor Disjunction
----------------------------------------------------------------------------------------------------------------------------------------------
7
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Value Types and Reference Types
A data type is a value type if it holds the data within its own memory allocation.
A reference type contains a pointer to another memory location that holds the data.
Value Types
Value types include the following:
All numeric data types
Boolean, Char, and Date
All structures, even if their members are reference types
Enumerations, since their underlying type is always SByte, Short, Integer, Long,
Byte, UShort, UInteger, or ULong
Reference Types
Reference types include the following:
String
All arrays, even if their elements are value types
Class types, such as Form
Delegates
----------------------------------------------------------------------------------------------------------------------------------------------
8
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Scope and lifetime of a variable
A scope of a variable is the part of the program or the block of the program in which it is
visible but outside that block the variable does not exist.
Lifetime of a variable defines the time for which the variable exists in a program.
When you declare a variable within a procedure, only code within that procedure can read
or change the value of that variable: Its scope is local to that procedure. Sometimes,
however, you want to use a variable with a broader scope, one whose value is available to
all procedures within the same module, or even to all the procedures in all modules. With
Visual Basic, you can specify the scope of a variable when you declare it.
Scope of Variables
Depending on how you declare a variable, its either a procedure-level or a module-level
variable.
Scope is Private or Public
Procedure-level Variables are private to the procedure in which they appear. Not
applicable. You cant declare public variables within a procedure.
Module-level Variables are private to the module in which they appear. Variables are
available to all modules.
Lifetime of Variables
The lifetime of a variable represents the period of time during which it can hold a value. Its
value can change over its lifetime, but it always holds some value.
A variable declared at module level typically exists for the entire time your application is
running. A nonshared variable declared in a class or structure exists as a separate copy for
each instance of the class or structure in which it is declared; each such variable has the
same lifetime as its instance. However, a Shared variable has only a single lifetime, which
lasts for the entire time your application is running.
Local variables declared with Dim exist only while the procedure in which they are declared
is executing. This applies also to that procedure's arguments and to any function return.
However, if that procedure calls other procedures, the local variables retain their values
while the called procedures are running.
----------------------------------------------------------------------------------------------------------------------------------------------
9
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Data Type Conversion
In Visual Basic, data can be converted in two ways: implicitly, which means the conversion is
performed automatically, and explicitly, which means you must perform the conversion.
Implict Conversions
Let's understand implicit conversions in code. The example below declares two variable, one of type
double and the other integer. The double data type is assigned a value and is converted to integer
type. When you run the code the result displayed is an integer value, in this case the value
displayed is 132 instead of 132.31223.
Imports System.Console
Module Module1
Sub Main()
Dim d=132.31223 as Double
Dim i as Integer
i=d
WriteLine("Integer value is" & i)
End Sub
End Module
Explicit Conversions
When types cannot be implicitly converted you should convert them explicitly. This conversion is
also called as cast. Explicit conversions are accomplished using CType function.
CType function for conversion
If we are not sure of the name of a particular conversion function then we can use the CType
function. The above example with a CType function looks like this:
Imports System.Console
Module Module1
Sub Main()
Dim d As Double
d = 132.31223
Dim i As Integer
i = CType(d, i)
'two arguments, type we are converting from, to type
desired
WriteLine("Integer value is" & i)
End Sub
End Module
Below is the list of conversion functions which we can use in VB .NET.
CBool - use this function to convert to Bool data type
CByte - use this function to convert to Byte data type
----------------------------------------------------------------------------------------------------------------------------------------------
10
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
CChar - use this function to convert to Char data type
CDate - use this function to convert to Date type
CDbl - use this function to convert to Double data type
CDec - use this function to convert to Decimal data type
CInt - use this function to convert to Integer data type
CLng - use this function to convert to Long data type
CObj - use this function to convert to Object type
CShort - use this function to convert to Short data type
CSng - use this function to convert to Single data type
CString - use this function to convert to String data type
Attributes
Attributes are those that lets us specify information about the items we are using in VB .NET.
Attributes are enclosed in angle brackets(< >) and are used when VB .NET needs to know more
beyond the standard syntax.
Language Terminology
Briefly on some terminology when working with the language:
Module: Used to hold code
Variable: A named memory location of a specific data type used to hold some value
Procedure: A callable series of statements which may or may not return a value
Sub-Procedure: A procedure with no return value
Function: A procedure with return value
Methods: A procedure built into the class
Constructor: Special method used to initialize and customize the object. It has the same name as
the class
Class: An OOP class which contains data and code
Object: An instance of a class
Arrays: Programming constructs that lets us access data by numeric index
Attributes: They are the items that specify information about other items being used in VB. NET
----------------------------------------------------------------------------------------------------------------------------------------------
11
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Conditionals and Loops
S|mp|e If 1hen
If w|th L|se
Public Class MainClass
Shared Sub Main()
Dim intNumber As Integer = 27
If intNumber = 27 Then
System.Console.WriteLine("'intNumber' is,
indeed, 27!")
End If
End Sub
End Class
Public Class MainClass
Shared Sub Main(ByVal args As String())
Dim valueOne As Integer = 10
Dim valueTwo As Integer = 20
Dim valueThree As Integer = 30
If valueOne > valueTwo Then
Console.WriteLine("ValueOne: {0} larger than ValueTwo: {
1}", valueOne, valueTwo)
Else
Console.WriteLine("Nope, ValueOne: {0} is NOT larger tha
n valueTwo: {1}", valueOne, valueTwo)
End If
End Sub
End Class
----------------------------------------------------------------------------------------------------------------------------------------------
12
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Se|ect L|se Demo
Public Class MainClass
Shared Sub Main()
'Determine which number was entered
Dim i As Integer
i = 10
Select Case i
Case 1
Console.WriteLine("The number 1 was entered")
Case 2
Console.WriteLine("The number 2 was entered")
Case 3
Console.WriteLine("The number 3 was entered")
Case 4
Console.WriteLine("The number 4 was entered")
Case 5
Console.WriteLine("The number 5 was entered")
Case Else
Console.WriteLine("A number other that 1 -
5 was entered")
End Select
End Sub
End Class
----------------------------------------------------------------------------------------------------------------------------------------------
13
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Ior Loop Demo (Sw|tch)
Ior |oop w|th step
Wh||e Loop
Public Class MainClass
Shared Sub Main(ByVal args As String())
Dim counter As Integer
While counter <= 10
' skip remaining code in loop only if counter = 7
If counter = 7 Then
Exit While
End If
counter += 1
End While
Console.WriteLine( "counter = " & counter & _
" after exiting While structure")
End Sub
End Class
Public Class MainClass
Shared Sub Main()
'Perform a loop
For intCount As Integer = 4 To 62 Step 7
'Add the item to the list
System.Console.WriteLine(intCount)
Next
End Sub
End Class
Public Class MainClass
Shared Sub Main()
'Count from 1 to 10
For intCount As Integer = 1 To 10
System.Console.WriteLine(intCount)
Next
'Count backwards from 10 to 1
For intCount As Integer = 10 To 1 Step -1
System.Console.WriteLine(intCount)
Next
End Sub
End Class
----------------------------------------------------------------------------------------------------------------------------------------------
14
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Do Wh||e Loop
public class MainClass
Shared Sub Main()
Dim cv As Integer = 0
Do While cv < 10
Console.WriteLine("counterVariable: {0}", cv )
cv = cv + 1
Loop
End Sub
End Class
----------------------------------------------------------------------------------------------------------------------------------------------
13
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Arrays
Arrays are programming constructs that store data and allow us to access them
by numeric index or subscript. Arrays helps us create shorter and simpler code in
many situations. Arrays in Visual Basic .NET inherit from the Array class in the
System namespace. All arrays in VB as zero based, meaning, the index of the
first element is zero and they are numbered sequentially. You must specify the
number of array elements by indicating the upper bound of the array. The upper
bound is the numder that specifies the index of the last element of the
array. Arrays are declared using Dim, ReDim, Static, Private, Public and
Protected keywords. An array can have one dimension (liinear arrays) or more
than one (multidimensional arrays). The dimensionality of an array refers to the
number of subscripts used to identify an individual element. In Visual Basic we
can specify up to 32 dimensions. Arrays do not have fixed size in Visual Basic.
The following code demonstrates arrays.
Imports System.Console
Module Module1
Sub Main()
Dim sport(5) As String
'declaring an array
sport(0) = "Soccer"
sport(1) = "Cricket"
sport(2) = "Rugby"
sport(3) = "Aussie Rules"
sport(4) = "BasketBall"
sport(5) = "Hockey"
'storing values in the array
WriteLine("Name of the Sport in the
third location" & " " & sport(2))
'displaying value from array
End Sub
End Module
Understanding the Code
The above code declared a sport array of type string like this: Dim sport(5) as
String. This sport array has 6 elements starting from sport(0) to sport(5). The
first element of an array is always referred by zero index. The image below
displays output from above code.
----------------------------------------------------------------------------------------------------------------------------------------------
16
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
You can also declare an array without specifying the number of elements on one
line, you must provide values for each element when initializing the array. The
following lines demonstrate that:
Dim Test() as Integer
'declaring a Test array
Test=New Integer(){1,3,5,7,9,}
Reinitializing Arrays
We can change the size of an array after creating them. The ReDim statement
assigns a completely new array object to the specified array variable. You
use ReDim statement to change the number of elements in an array. The
following lines of code demonstrate that. This code reinitializes the Test array
declared above.
Dim Test(10) as Integer
ReDim Test(25) as Integer
'Reinitializing the array
When using the Redim statement all the data contained in the array is lost. If you
want to preserve existing data when reinitializing an array then you should use
the Preserve keyword which looks like this:
Dim Test() as Integer={1,3,5}
'declares an array an initializes it
with three members
ReDim Preserve Test(25)
'resizes the array and retains the the
data in elements 0 to 2
Multidimensional Arrays
All arrays which were mentioned above are one dimensional or linear arrays.
There are two kinds of multidimensional arrays supported by the .NET
framework: Rectangular arrays and Jagged arrays.
Rectangular arrays
Rectangular arrays are arrays in which each member of each dimension is
extended in each other dimension by the same length. We declare a rectangular
array by specifying additional dimensions at declaration. The following lines of
code demonstrate the declaration of a multidimensional array.
----------------------------------------------------------------------------------------------------------------------------------------------
17
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Dim rectArray(4, 2) As Integer
'declares an array of 5 by 3 members which is a
15 member array
Dim rectArray(,) As Integer = {{1, 2, 3}, {12,
13, 14}, {11, 10, 9}}
'setting initial values
Jagged Arrays
Another type of multidimensional array, Jagged Array, is an array of arrays in
which the length of each array can differ. Example where this array can be used
is to create a table in which the number of columns differ in each row. Say, if
row1 has 3 columns, row2 has 3 columns then row3 can have 4 columns, row4
can have 5 columns and so on. The following code demonstrates jagged arrays.
Dim colors(2)() as String
'declaring an array of 3 arrays
colors(0)=New String(){"Red","blue","Green"}
initializing the first array to 3 members and
setting values
colors(1)=New
String(){"Yellow","Purple","Green","Violet"}
initializing the second array to 4 members
and setting values
colors(2)=New
String(){"Red","Black","White","Grey","Aqua"}
initializing the third array to 5 members and
setting values
----------------------------------------------------------------------------------------------------------------------------------------------
18
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
String Class
String represents text; that is, a series of Unicode characters.
Various properties and methods of String class are:
Chars
Gets the character at a specified character position in the string.
Dim s As String = "welcome"
Console.WriteLine(s.Chars(3)) 'c
Length
Gets the number of characters.
Dim s As String = "welcome"
Dim i As Integer
i = s.Length
Console.WriteLine ("length = " & i) '7
Comparing-Strings
The Compare method compares two strings and returns an integer value
Dim s = "welcome", s1 = "Welcome"
Dim i As Integer
i = String.Compare (s, s1)
Console.WriteLine (i) '-1
s = "welcome" s1 = "welcome"
i = String.Compare (s, s1)
Console.WriteLine (i) '0
s = "Welcome"
s1 = "welcome"
i = String.Compare (s, s1)
Console.WriteLine (i) '1
Concat
The Concat method adds strings (or objects) and returns a new string.