Basic Data Types and their mapping to the CTS (Common Type System)
There are two kinds of data types in VB.Net
1. Value type (implicit data types, Structure and Enumeration)
2. Reference Type (objects, delegates)
Value types are passed to methods by passing an exact copy while Reference types are passed to methods by passing only their reference (handle). Implicit data types are defined in the language core by the language vendor, while explicit data types are types that are made by using or composing implicit data types.
As we saw in the first lesson, implicit data types in .net compliant languages are mapped to types in Common Type System (CTS) and CLS (Common Language Specification). Hence, each implicit data type in VB.Net has its corresponding .Net type. The implicit data types in VB.Net are:
| VB.Net type | Corresponding .Net type | Size in bytes | Description |
| Boolean | Boolean | 1 | Contains either True or False |
| Char | Char | 2 | Contains any single Unicode character enclosed in double quotation marks followed by a c, for example "x"c |
| Integral types | | | |
| Byte | Byte | 1 | May contain integers from 0-255 |
| Short | Int16 | 2 | Ranges from -32,768 to 32,767 |
| Integer(default) | Int32 | 4 | Ranges from -2,147,483,648 to 2,147,483,647 |
| Long | Int64 | 8 | Ranges from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. |
| Floating point types | | | |
| Single | Single | 4 | Ranges from ±1.5 × 10-45 to ±3.4 × 1038 with 7 digits precision. Requires the suffix 'f' or 'F' |
| Double(default) | Double | 8 | Ranges from ±5.0 × 10-324 to ±1.7 × 10308 with 15-16 digits precision. |
| Decimal | Decimal | 12 | Ranges from 1.0 × 10-28 to 7.9 × 1028 with 28-29 digits precision. Requires the suffix 'm' or 'M' |
Implicit data types are represented in language using 'keywords'; so each of above is a keyword in VB.Net (Keyword are the words defined by the language and can not be used as identifiers). It is worth-noting that string is also an implicit data type in VB.Net, so String is a keyword in VB.Net. Last point about implicit data types is that they are value types and thus stored at the stack, while user defined types or referenced types are stored at heap. Stack is a data structure that store items in last in first out (LIFO) fashion. It is an area of memory supported by the processor and its size is determined at the compile time. Heap is the total memory available at run time. Reference types are allocated at heap dynamically (during the execution of program). Garbage collector searches for non-referenced data in heap during the execution of program and returns that space to Operating System.
Variables
During the execution of program, data is temporarily stored in memory. A variable is the name given to a memory location holding particular type of data. So, each variable has associated with it a data type and value. In VB.Net, a variables is declared as:
Code:
Dim <variable> as <data type>
Example:
The above line will reserve an area of 4 bytes in memory to store integer type values, which will be referred in the rest of program by identifier 'i'. You can initialize the variable as you declare it (on the fly) and can also declare/initialize multiple variables of same type in a single statement, e.g.,
Code:
Dim isReady As Boolean = True
Dim percentage = 87.88, average = 43.9 As Single
Dim digit As Char = "7"c
VB.Net Option Strict and Option Explicit Settings
There are two 'bad' features in VB.Net, which are inherent from earlier versions (VB5 and VB6):
* You can declare a variable without specifying its type. VB.Net, in this case, assumes the type of the variable as System.Object class
* You can convert values (or objects) to incompatible types, e.g., String to Integer.
Why I called the two options bad? The use of these two features results in quite a number of bugs and makes the overall design of application bad, complex and difficult to follow. With incompatible type conversion, the program does compile without any error but throw a runtime error (exception). But these two features can be turned off by using the Option Explicit and Option Strict statements.
Option Explicit Statement
Option Explicit, when turned on, do not allow to use any variable without proper declaration.
There are two methods to apply the Option Explicit Statement.
* To apply the Option Explicit settings to the complete project in Visual Studio.Net, right click the project name in the solution explorer and select Properties. It will open the Property Pages window. Now in the Common Properties tree at left, select Build, it will show the following window
From here, you can turn the Option Explicit (as well as Option Strict) on or off.
To apply the Option Explicit settings to the current file, use the Option Explicit statement before any statement as,
When Option Explicit is on, it will cause the compile time error to write
Code:
myName = "Faraz" ' compile time error with Option Explicit On
Rather, you would have to write,
Code:
Dim myName As String = "Faraz"
Option Strict Statement
When the Option Strict statement is turned on, incompatible type conversion are not allowed. Option Strict can be turned on or off in the similar fashion as Option Explicit. You can either use Option Strict Statement as
Or you can set it from the project properties. When Option Strict is On, the following program will cause a compile time error
Code:
Sub Main()
Dim strNum As String = "1"
Dim intNum As Integer = strNum
Console.WriteLine(intNum)
End Sub
But if the Option Strict is turned off, the above program will actually compile and run without error to print 1 on the Console!
It is important to remember that Option Strict also does not allow using un-declared types and hence there is no use turning the Option Explicit on if you are already using Option Strict.
Finally, we do not discourage our readers to turn Option Explicit and Option Strict off; It's strongly advised not to do so! Throughout the VB.Net School, we will implicitly assume that the Option Strict is turned On
Constant or Symbols
Constants values once defined cannot be changed in the program. Constants are declared using Const keyword, like:
Code:
Dim Const PI As Double = 3.142
Constants must be initialized as they are declared.
Code:
Dim Const MARKS As Integer
It is a notation convention to use capital letters while naming constants.
Naming Conventions for variables and methods
Microsoft suggests using Camel Notation (first letter in lowercase) for variables and Pascal Notation (first letter in uppercase) for methods. Each word after the first word in the name of both variable and method should start with capital letter. For example, variable names following Camel notation could be
Code:
salary totalSalary
myMathsMarks isPaid
Some typical names of method following Pascal Notation are
Code:
GetTotal() Start()
WriteLine() LastIndexOf()
Although it is not mandatory to follow this convention, it is highly recommended to follow it. Microsoft no longer uses Hungarian notation. An example wooul be "iMarks" for an integer variable. Also, using underscores _ in names is also not encouraged.
Breaking lines in VB.Net
The VB.Net compiler identifies the end of statement by the end of line. Hence, it is not possible to write a single statement on multiple lines (as done in C/C++, Java, C#). The following code will raise a syntax error:
Code:
Dim myName As String = "My name is
Faraz Rasheed"
The compiler treats the two lines as two instructions and will cause syntax errors upon finding these two lines. To expand a single statement on to multiple lines, you must use the underscore _ character at line breaks. For example, the above code is perfectly valid when modified as below
Code:
Dim myName As String = "My name is " & _
"Faraz Rasheed and, " & _
"I like .Net as ..."
Console.WriteLine(myName)
The above code fragment will result in following output at Console
My name is Faraz Rasheed and, I like .Net as...
Operators in VB.Net
Arithmetic Operators
Several common arithmetic operators are allowed in VB.Net like
+ (add)
- (subtract)
* (multiply)
/ (divide)
Mod (remainder or modulo)
The program below uses these operators
Code:
Imports System
Module ArithmeticOperators
' The program shows the use of arithmetic operators
' + - * / Mod
Sub Main()
' result of addition, subtraction, multiplication and modulus operator
Dim sum, difference, product, modulo As Integer
sum = 0
difference = 0
product = 0
modulo = 0
Dim quotient As Double = 0 ' result of division
Dim num1 As Integer = 10 ' operand variables
Dim num2 As Integer = 2
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
modulo = 3 Mod num2 ' remainder of 3/2
Console.WriteLine("num1 = {0}, num2 = {1}", num1, num2)
Console.WriteLine()
Console.WriteLine("Sum of {0} and {1} is {2}", num1, num2, sum)
Console.WriteLine("Difference of {0} and {1} is {2}", num1, num2, difference)
Console.WriteLine("Product of {0} and {1} is {2}", num1, num2, product)
Console.WriteLine("Quotient of {0} and {1} is {2}", num1, num2, quotient)
Console.WriteLine()
Console.WriteLine("Remainder when 3 is divided by {0} is {1}", num2, modulo)
End Sub
End Module
Although the program above is quite simple, Lets discuss some concepts. In the Console.WriteLine() method, we have used format-specifiers {int} to indicate the position of variables in the string.
Code:
Console.WriteLine("Sum of {0} and {1} is {2}", num1, num2, sum)
Here, {0}, {1} and {2} will be replaced by the values of num1, num2 and sum variables. In {i}, i specifies that the (i+1)th variable after the double quotes will replace it when printed on the Console. Hence, {0} will be replaced by first, {1} will be replaced by second variable and so on.
Assignment Operators
Assignment operators are used to assign values to variables. Common assignment operators in VB.Net are:
= (simple assignment)
+= (additive assignment) -= (subtractive assignment)
* = (multiplicative assignment) /= (division assignment)[/pre]
The Equal operator is used to assign a value to a variable or a reference. For example, the instruction
Code:
Dim isPaid As Boolean = false
assigns the value 'False' to the isPaid variable of Boolean type. The Left and right hand side of the equal or any other assignment operator must be compatible otherwise the compiler will complain of a syntax error.
Sometimes casting is used for type conversion, e.g., to convert and store values in a variable of type Double to a variable of type Integer. We need to apply integer cast using VB.Net's CType() built-in method
Code:
Dim doubleValue As Double = 4.67
Dim intValue As Integer = CType(doubleValue, Integer) ' intValue would be equal to 4
The method CType() is used for compatible type conversions. It takes two arguments; the first being the source variable to convert to, while the second argument is the target type of conversion. Hence, the above call to the method CType() will convert the value in the variable 'doubleValue' of type Double to a variable of type Integer and will return the converted Integer type value that will be stored in the Integer variable 'intValue'
Of course, with narrow casting (from bigger type to smaller type) there is always a danger of some loss of precision; as in the case above, we only got 4 of the original 4.67.
Code:
Dim intValue As Integer = 32800
Dim shortValue As Short = CType(intValue, Short)
When the second of these lines is run an error will be given, stating that "Arithmetic operation resulted in an overflow." Why is it so? Variables of type Short can only take a maximum value of 32767. The cast above can not assign 32800 to a shortValue. This is detected at runtime and an error is given.
If you try to do an invalid cast of incompatible types like below
Code:
Dim strValue As String = "Faraz"
Dim intValue As Integer = CType(strValue, Integer)
Then again it will get compiled but will crash the program at runtime.
Relational Operators
Relational operators are used for comparison purposes in conditional statements. The common relational operators in VB.Net are:
= (equality check) <> (un-equality check)
> (greater than) < (less than)
>= (greater than or equal to) <= (less than or equal to)
Relational operators always result in a Boolean statement; either True or False. For example if we have two variables
Code:
Dim num1 = 5, num2 = 6 As Integer
then,
num1 = num2 will result in false
num1 <> num2 will result in true
num1 > num2 will result in false
num1 < num2 will result in true
num1 <= num2 will result in true
num1 >= num2 will result in false
Only compatible data types can be compared. It is invalid to compare a Boolean with an Integer, if
Code:
Dim i = 1 As Integer
Dim b = True As Boolean
then it is a syntax error to compare i and b for equality (i=b)
Logical and Bitwise Operators
These operators are used for logical and bitwise calculations. The common logical and bitwise operators in VB.NET are:
And (bitwise AND) Or (bitwise OR)
Xor (bitwise XOR) Not (bitwise NOT)
AndAlso (Logical or short circuit AND) OrElse (Logical or short circuit OR)
The operators And, Or and Xor are rarely used in usual programming practice. The Not operator is used to negate a Boolean or bitwise expression like:
Code:
Dim b = False As Boolean
Dim bb As Boolean = Not b ' bb would be true
Logical Operators And, Or, AndAlso and OrElse are also used to combine comparisons like
Code:
Dim i=6, j=12 As Integer
Dim firstVar As Boolean = i>3 And j < 10 ' firstVar would be false
Dim secondVar As Boolean = i>3 Or j < 10 ' secondVar would be true
In the first comparison case: i>3 And j<10 will result in true only if both the conditions i>3 and j<10 result in true. While in the second comparison: i>3 Or j<10 will result in true if any of the conditions i>3 and j<10 result in true. You can of course use the combination of And, Or, AndAlso and OrElse in a single statement like:
Code:
bool firstVar = (i>3 And j<10) OrElse (i<7 And j>10)
'firstVar would be true
In the above statement we used brackets to group our conditional expressions to avoid any ambiguity.
You can also use And and Or operators in place of AndAlso and OrElse respectively; but for combining conditional expressions, AndAlso and OrElse are more efficient as they use "short circuit evaluation", i.e., if in (i>3 AndAlso j<10) expression, i>3 evaluates to false, it would not check the second expression j<10 and will return false (as in AND, if one of the participant operand is false, the whole operation will result in false). Hence, one should be very careful to use assignment expressions with AndAlso and OrElse operators. The And and Or operators don't do short circuit evaluation and do execute all the comparisons before returning the result.
Other Operators
There are other operators present in VB.Net. A short description of these is given below:
(member access for objects) () (indexing operator used in arrays and collections)
Operator Precedence
All operators are not treated equally. There is a concept of operator precedence in VB.Net as in
Code:
Dim i As Integer = 2 + 3 * 6 ' i would be 20 not 30
3 will be multiplied by 6 first then the result will be added to 2. This is because the multiplication operator * has precedence over the addition operator +. For a complete table of operator precedence, consult msdn or the .net framework documentation.
Flow Control And Conditional Statements
If…Then…Else statement
Condition checking has always been the most basic and important construct in any language. VB.Net provides conditional statements in the form of the If...Then...Else statement. The structure of this statement is:
Code:
If Boolean expression Then
Statement or block of statement
Else
Statement or block of statement
End If
The Else clause above is optional. The typical example is
Code:
If i=5 Then
Console.WriteLine("Thanks God, i finally becomes 5")
End If
In the above example, the console message will be printed only if the expression i=5 evaluates to True. If action is needed in the case when the condition does not evaluate to true you can use the Else clause.
Code:
If i=5 Then
Console.WriteLine("Thanks God, I finally becomes 5")
Else
Console.WriteLine("Missed...When will I become 5?")
End If
Only the first message will be printed in the case of i being 5. In any other case (when i is not 5), the second message will be printed. You can also use a block of statements (more than one statement) under any If and Else.
Code:
If i=5 Then
j = i*2
Console.WriteLine("Thanks God, i finally becomes 5")
Else
j = i/2
Console.WriteLine("Missed...When will i become 5?")
End If
You may write If...Then or If...Then...Else in the single line, like
Code:
If i=5 Then Console.WriteLine("Thanks God, I finally became 5")
As you might have picked from the above two statements. When an If...Then and If...Then...Else are used on the same line, we do not need to write an End If. The reason is quite simple; End is used to mark the end of a block in VB.Net. With these two statements, we do not create or use any blocks of statements
I would always recommend to use If...Then and If...Then...Else statements in block format with End If. It increases the readability and prevents many bugs that otherwise can be produced in the code.
You can also have an If after an Else for further conditioning
Code:
If i=5 Then 'line 1
Console.WriteLine("Thanks God, i finally becomes 5")
ElseIf i=6 'line 3
Console.WriteLine("Ok, 6 is also closer to 5")
Else 'line 5
Console.WriteLine("Missed...When will i become 5 or closed to 5?")
End If
ElseIf i=6 is executed only if the first condition i=5 is false. An Else at line 5 will be executed only if the second condition i=6 (line 3) executes and fails (that is both the first and second condition fails). The point being is that Else at line 5 is related to the If on line 3
As If...Then...Else is also an statement, you can use it under other If...Then...Else statements, like:
Code:
If i>5 Then ' line 1
If i=6 Then ' line 2
Console.WriteLine("Ok, 6 is also closer to 5")
Else ' line 4
Console.WriteLine("Oops! i is greater than 5 but not 6")
End If
Console.WriteLine("Thanks God, i finally becomes greater than 5")
Else ' line 8
Console.WriteLine("Missed...When will i become 5 or closed to 5?")
End If
The Else on line 4 is clearly related to the If...Then on line 2 while the Else on line 8 belongs to the If on line 1. Finally, do note (VB6 and C/C++ programmers especially) that the If statement expects only Boolean expression and not an Integer value. It is indeed an error to write
Code:
Dim flag As Integer = 0
If flag Then
' do something...
End If
Instead, you can either use
Code:
Dim flag As Integer = 0
If flag = 1 Then ' note ==
' do something…
End If
or
Code:
Dim flag As Boolean = False
If flag Then ' Boolean expression
' do something...
End If
The key to avoid confusion when using a complex combination of If...Then...Else is the
Select…Case statement
If you need to perform a series of specific checks, Select...Case is present in VB.Net and is just the ticket for this. The general structure of Select...Case statement is as follows:
Code:
Select <any implicit data type expression>
Case expression
statements
' some other case blocks
...
Case Else
statements
End Select
It takes much less time to use the Select...Case than using several If...Then...ElseIf statements. Let's understand it with an example
Code:
Imports System
' To execute the program write "SwitchCaseExample 2" or
' any other number at command line,
' if the name of .exe file is "SwitchCaseExample.exe"
Module ArithmeticOperators
' Demonstrates the use of switch...case statement along with
' the use of command line argument
Sub Main(ByVal userInput() As String)
' convert the string input to integer
' Will through run-time exception if there is no input
' at run-time or input is not castable to integer
Dim input As Integer = Integer.Parse(userInput(0))
Select Case input ' what is input?
Case 1 ' if it is 1
Console.WriteLine("You typed 1 (one) as first command line argument")
Case 2 ' if it is 2
Console.WriteLine("You typed 2 (two) as first command line argument")
Case 3 To 5 ' if it is 3
Console.WriteLine("You typed number from 3 (three) to
five (five) as first command line argument")
Case Else ' if it is not of the above
Console.WriteLine("You typed other than 1, 2, 3, 4 and 5")
End Select
End Sub
End Module
An integer must be supplied for the command line argument. Firstly, compile the program (at command line or in Visual Studio.Net). Suppose we made an exe with name "SelectCaseExample.exe". Now run it at the command line like so:
C:\>VBDotNetSchoolLesson3 2
You typed 2 (two) as command line argument
or,
C:> VBDotNetSchoolLesson3 4
You typed number from 3 (three) to five (five) as first command line argument
or,
C:> VBDotNetSchoolLesson3 7
You typed other than 1, 2, 3, 4 and 5
If you did not enter any command line argument or give a non-integer argument, the program will raise an exception
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at VBDotNetSchoolLesson3.ArithmeticOperators.Main(Str ing[] userInput) in C:\Documents and Settings\farazr.YEVOLVE\My Documents\Visual Studio Projects\VBDotNe tSchoolLesson3\Module1.vb:line 14
Lets come to the internal workings. We converted the first command line argument (userInput(0)) into an Integer variable input. For conversion, we used static Parse() method of the Integer data type. This method takes a String and returns an equivalent integer or raises an exception if the conversion can’t be completed. Next we checked the value of input variable using switch the statement
Code:
Select Case input
...
End Select
Later on in the basis of the input values, we took specific actions under the respective case statements. Case 1 ' if it is 1 Console.WriteLine("You typed 1 (one) as the first command line argument")
We can also specify a range in the Case Expression to match
Code:
Case 3 To 5 ' if it is 3
Console.WriteLine("You typed number from 3 (three)
to five (five) as first command line argument")
If all the specific checks fail (input is neither 1,2,3,4 or 5), the statements under “Case Else” will execute.
Code:
Case Else ' if it is not of the above
Console.WriteLine("You typed other than 1, 2, 3, 4 and 5")
There are some important points to remember when using switch…case statement in VB.Net
* You can use any implicit data type in the Select statement
* You can use multiple statements under a single case statement as follows
Code:
Case "Pakistan"
continent = "Asia"
Console.WriteLine("Pakistan is an Asian Country")
Case Else
continent = "Un-recognized"
Console.WriteLine("Un-recognized country discovered")
* Statements under Case Else will only be executed if and only if all Case checks fail.
* You can't have more than one Case Else block in a single Select statement.
Loops In VB.Net
Loops are used for iteration purposes, i.e., performing a task multiple times (usually until a termination condition is met)
For…Next Loop
The most common type of loop in VB.Net is the For...Next loop. The basic structure of the For...Next loop is exactly the same as in VB6 and is like so:
Code:
For variable = startingValue To lastValue
statement or block of statements
Next
Lets see a For...Next loop that will write integers from 1 to 10 on the console
Code:
Dim i As Integer
For i = 1 to 10
Console.WriteLine("In the loop, value of i is " & i)
Next
At the start, an integer variable i is initialized with the value of 1, then the statements under the For are executed until the value of i does not equal 10. Each time i is incremented by 1.
The important points about for loop are:
* You can use an Exit For statement in a For...Next loop or any other loop to change the normal execution flow
* An Exit For statement terminates the loop and transfers the execution point outside the for loop as below:
Code:
For i=1 to 10
If i>5 Then
Exit For
End If
Console.WriteLine("In the loop, value of i is {0}.", i)
Next
The loop will terminate once the value of i gets greater than 5. If some statements are present after Exit For, it should be enclosed under some conditions. Otherwise the lines following the break point will not execute
Code:
For i = 1 To 10
Exit For
Console.WriteLine()
Next
You can define the increment/decrement (change) in each iteration of a For...Next Loop using the Step statement. The code below will increment by 2 in the value of i in each cycle of the loop
Code:
For i = 1 To 10 Step 2
Console.WriteLine("Value of i is {0}", i)
Next
The following is the output on the Console,
Value of i is 1
Value of i is 3
Value of i is 5
Value of i is 7
Value of i is 9
Press any key to continue Note that the increment starts after the first iteration. You can also specify the negative increment (i.e., decrement) in a Step. The following code will output Integers from 10 to 1
Value of i is 10
Value of i is 9
Value of i is 8
Value of i is 7
Value of i is 6
Value of i is 5
Value of i is 4
Value of i is 3
Value of i is 2
Value of i is 1
Press any key to continue
Do While…Loop
The general structure of the Do While...Loop is
Code:
Do While Boolean expression
Statement or block of statements
Loop
The statements under Do While will run continuously as long as the Boolean expression evaluates to true. The similar code for printing integers 1 to 10 on Console using the Do While...Loop is
Code:
Dim i As Integer =1
Do While i<=10
Console.WriteLine("In the loop, value of i is " & i)
i = i + 1
Loop
Do…Loop While
A Do...Loop While is similar to a Do While...Loop, except that it does not check the condition before entering the first iteration (execution of code inside the body of loop). The general form of the a Do...Loop While is:
Code:
Do
statement or block of statements
Loop While Boolean expression
The statements under the Do will be executed first and then the Boolean condition is checked. The loop will continue until the condition remains true. The code which prints integers 1 to 10 on console using Do...Loop While is
Code:
Dim i As Integer = 1
Do
Console.WriteLine("In the loop, value of i is " & i)
i = i + 1
Loop While i<=10
The important point is that the statements in a Do...Loop While execute at least once.
Do…Loop Until
A Do...Loop Until is similar to the Do...Loop While, except that it continues to execute the containing statements until the condition against the Until part evaluates to True or the condition against the Until remains False. The general form of the Do...Loop Until is as follows:
Code:
Do
statement or block of statements
Loop Until Boolean expression
The statements under the Do will execute first and then the condition is checked. The loop will continue until the condition remains false. The following code will print integers from 1 to 10 on console using the Do...Loop Until.
Code:
Dim i As Integer = 1
Do
Console.WriteLine("In the loop, value of i is " & i)
i = i + 1
Loop Until i=10
Again the statements in Do...Loop Until execute at least once.
Arrays in VB.Net
Declaration
An Array is a collection of values of similar data type. Technically, VB.Net arrays are of reference type. Each array in VB.Net is an object and is inherited from the System.Array class. Arrays are declared as follows:
Code:
Dim <identifier>(<size of array>) As <data type>
Lets define an array of Integer type to hold 10 integers.
Code:
Dim myIntegers(9) As Integer
The above will create an array of 10 integers from the index of 0 to 9. The size of an array is fixed and must be defined before use. You can also use variables to define the size of array like so:
Code:
Dim size As Integer = 10
Dim myIntegers(10-1) As Integer
You can optionally perform declaration and initialization in separate steps like below:
Code:
Dim myIntegers() As Integer
myIntegers = New Integer() {1, 2, 3, 4, 5}
Here we initialized the array myIntegers using the values it holds. Note, we must enclose the values in curly brackets and separate the individual values with commas. This will create an array size of 5, whose successive values will be 1, 2, 3, 4, 5
It is important to note that when an array declaration and initialization are performed separately, you must provide values for each element.
Accessing the values stored in array
To access the values in an Array, we use the indexing operator (Integer index) by passing an Integer to indicate which particular index value we wish to access. It's important to note that index values in VB.Net starts from 0. So, if an array contains 5 elements, first element would be at index 0, second at index 1 and last (fifth) at index 4. The following code demonstrates how to access the 3rd element of an array
Code:
Dim myIntArray() As Integer
myIntArray = New Integer() {5, 10, 15, 20}
Dim j As Integer = myIntArray(2)
Lets make a program that uses an integral array.
Code:
' demonstrates the use of arrays in VB.Net
Public Sub Main()
' declaring and initializing an array of type integer
Dim myIntegers() As Integer = New Integer() {3, 7, 2, 14, 65}
' iterating through the array and printing each element
Dim i As Integer
For i = 0 to 4
Console.WriteLine(myIntegers(i))
Next
End Sub
Here we used the For...Next loop to iterate through an array and use the Console.WriteLine() method to print each individual element of the array. Note how the indexing operator () is used.
The above program is quite simple and efficient, but we have to hard-code the size of the array in the For...Next loop. As we mentioned earlier, arrays in VB.Net are reference type and are a sub-class of the System.Array Class. This class has a lot of useful properties and methods that can be applied to any instance of an array. Properties are very much like a combination of getter and setter methods in common Object Oriented languages. Properties are context sensitive; meaning the compiler can un-ambiguously identify whether it should call a getter or a setter in certain contexts. We will discuss properties in detail in the coming chapters. System.Array has a very useful read only property “Length” that can be used to find the length or the size of an array programmatically. Using the Length property, the For...Next loop from the previous code example can be written as follows
Code:
For i = 0 to myIntegers.Length - 1
Console.WriteLine(myIntegers(i))
Next
This type of loop is very flexible and can be applied to an array of any size and of any data-type.
We can also understand the common description of the Main() Sub procedure. Main is also declared as
Code:
Public Main(ByVal args As String())
The command line arguments that we pass when executing our program are available in our programs through an array of String type, which is identified by args string array.
The For Each Loop
There is another type of loop that is very simple and useful to iterate through arrays and other collections. This is a For Each loop. The basic structure of the For Each loop is
Code:
For Each <identifier> in <array or collection>
<statements or block of statements>
End For
Lets now make our previous code iterate through an array with a For Each loop
Code:
' demonstrates the use of arrays in VB.Net
Public Sub Main()
' declaring and initializing an array of type integer
Dim myIntegers() As Integer = New Integer() {3, 7, 2, 14, 65}
' iterating through the array and printing each element
Dim i As Integer
For Each i in myIntegers
Console.WriteLine(i)
Next
End Sub
Simple and more readable! Isn't it?
Code:
For Each i in myIntegers
We declared the variable 'i' to hold individual values of array 'myIntegers' in each iteration. It is necessary to specify the type of variable 'i' same as the type of elements in the collection (Integer in our case).
Important points to note here are
* Variables are used to hold individual elements of an array in each iteration (i in the above example) are readonly. You can't change the elements of an array through it, you can only read it. This means For Each only allows you to iterate through the array or collection and not to change the contents of it. If you wish to perform some work on array elements such as to change the individual elements, you should use the For...Next loop.
* For Each can be used to iterate through arrays or collections. By collection, we mean any class, struct or interface that implements an IEnumerable interface. (Just go through this point and come back to it once we complete the lesson describing classes and interfaces)
* The String class is also a collection of characters (implements IEnumerable interface and returns the Char value in the Current property). The following code example demonstrates this and prints all the characters of a string.
Code:
Public Sub Main()
Dim name As String = "Faraz Rasheed"
Dim ch As Char
For Each ch in name
Console.WriteLine(ch)
End For
End Sub
This will print each character of the name variable on a separate line.
Lesson #3 coming soon!