Welcome to my guide on mastering Visual Basic .NET
I used Visual Studio Ultimate 2010 while creating this, and you can download a trial for free at [Only registered and activated users can see links. Click Here To Register...] or find a cracked version on the web. I created this guide specifically for silkroad online gamers and coders. I am guiding the exact way I learned. I am very limited on time, so I will post lessons when I can. I have a total of 14 lesons, and I will always keep the post up to date on my latest lesson I posted.
Current Lesson #: 2
Lesson #1
Lesson #2
I used Visual Studio Ultimate 2010 while creating this, and you can download a trial for free at [Only registered and activated users can see links. Click Here To Register...] or find a cracked version on the web. I created this guide specifically for silkroad online gamers and coders. I am guiding the exact way I learned. I am very limited on time, so I will post lessons when I can. I have a total of 14 lesons, and I will always keep the post up to date on my latest lesson I posted.
Current Lesson #: 2
Lesson #1
Writing Your First "Hello World" Console Application in VB.Net
As follows, we will build our first VB.Net application without and then with Visual Studio.Net. Instructions below show, how to write, compile, and execute a VB.Net application.
Without Visual Studio.Net
Open "Notepad" or a text editor of your choice and type the following code:
Save this with any file name with the extension ".vb" (for example, 'MyFirstApplication.vb'). To compile the program, go to Visual Studio command prompt and type:
Note: You may have to change the directory to where you saved your file.
This will compile your program and create an .exe file (MyFirstApplication.exe) in the same directory. Errors will be reported if there are any. To run your program, type:
(or whatever you named it)
This action will print "Hello World!" on the console screen.
With Visual Studio.Net
Start Microsoft Visual Studio.Net and from the menu select File > New > Project. A "New Project" dialog will now be displayed. Select "Visual Basic Project" from "Project Type" and select "Console Application" from "Templates". Type "MyHelloWorldApplication" (without "") in the "Name" text box below, then click OK.
Change the name of module from Module1 to "MyHelloWorldApplication" and type
To compile and execute your application, select "Start" from the "Debug" menu or to run the application without Debug press Ctrl+F5. A new console window containing the words Hello World will now be displayed. Press any key to terminate the program and close the console window.
Let's build on this code and include some more VB.NET syntax. Modify your code as below:
Understanding the Hello World Application Code:
The first line of our program (Imports System) usually appears in all VB.Net programs. It gives us access to the core functionality of programming. This shall be covered later. Before then, the second line (Namespace MyHelloWorldApplication) shall be discussed.
Namespaces in VB.Net
A namespace is simply a logical collection of related classes in VB.Net. We bundle our related classes (like those related with database activity for example) in a named collection, hence calling it a namespace (e.g., DataActivity).
VB.Net does not allow two classes with the same name to be used in a program. The sole purpose of using namespaces is to prevent the name conflict, which may happen if your working with a large number of classes. It is the same case in the Framework Class Library (FCL). It is highly possible that the Connection Class in DataActivity conflicts with the Connection Class of InternetActivity. To avoid this, these classes are made part of their respective namespace. The fully qualified name of these classes will be DataActivity.Connection and InternetActivity.Connection, hence resolving any ambiguity for the compiler.
In the second line of the code there is a declaration classes (enclosed in Namespace...EndNamespace block) which are part of the MyHelloWorldApplication namespace.
The VB.Net namespaces have NO physical mapping, as is the case in Java. Classes within the same namespace can be in different folders. The C# concept of mapping is similar to "packages" in Java and "namespace" in standard C++. The namespace may contain modules, classes, interfaces, events, exceptions, delegates and even other namespaces which are known as "Internal namespace". These internal namespaces can be defined like this:
The Imports Keyword
The first line of our program is
The "Imports" keyword in the code sample above enables us to use classes in the "System" namespace. For example, Its possible to access the Console class from the Main() sub. One point to remember here is that "Imports" allows access to classes in the referenced namespace only and not in its internal/child namespaces. Hence we might need to write:
In order to access the classes defined in Collection namespace which is a sub/internal namespace of the System namespace.
The Module Keyword
A VB.Net program may contain one or more modules. The Main() sub-procedure usually resides in one of these modules. Modules in VB.Net are a combination of general data (fields) and general functions (methods) that are accessible to any code that can access the namespace of a module. All the members (fields, methods, properties) defined inside a module are shared by default.
The concept of a Module will be discussed in more detail in future lessons. Modules in VB.Net are defined using the Module statement, followed by the name of the module. The end of a module is marked with the End Module statement.
This is the standard layout of a Main sub-procedure within a VB.Net module. The Main() sub-procedure is the entry point of a program, i.e. a VB.Net program starts its execution from the first line in the Main sub-procedure and ceases to exist with the termination of the Main sub-procedure. We can also define the Main method inside a class, e.g.
The main sub-procedure is designated as "Shared" as it can be called by the Common Language Runtime (CLR) without creating any objects from our MyHelloWorldClass (this is the definition of Shared methods, fields and properties). The sub-procedure is also declared as "Public" so that classes outside its namespace and assembly may call this method. Main is the (standard) name of this method. More evidence of this shall be shown later.
One interesting point is that it is legitimate to have multiple Main() methods in VB.Net program. However, you have to explicitly identify which Main method is the entry point for the program.
Printing on the Console
The next line of code prints "Hello World" on the Console screen:
In the code,WriteLine() is called. It is a "Shared" method of the Console class that is defined in the System namespace. This method takes a string (enclosed in double quotes) as its parameter and prints it on the Console window.
VB.Net, like other Object Oriented languages, uses the dot (.) operator to access the member variables (fields) and methods of a class. Also, parenthatsis () are used to identify methods in the code. String literals are enclosed in double quotation marks ("). Lastly, it must be remembered that VB.Net is a case-insensitive language; hence Console and conSole are the same words (identifiers) in VB.Net.
Comments
Comments are created by programmers who wish to explain the code. Comments are ignored by the compiler and are not included in the executable code. VB.Net uses similar syntax for comments as used in VB and assembly language. The text following a single quotation mark (' any comment) is a line comment. the ending is the end of the line.
Important points to remember
A more interactive Hello World Application
Up to this point we have seen a very static Hello World application that greets the whole world when it is executed. Lets now make a more interactive hello world that greets its current user. This program will ask the user's name and will greet them using their name, like 'Hello Faraz', when the user named 'Faraz' runs it. Let's see the code first:
Discussing a more interactive Hello World Application
In the first line of Main, there is another method, Write(). Which is part of the Console class. This is similar to the WriteLine() method discussed in the previous program, but the cursor does not move to a new line after printing the string on the console.
In the second line, there is a declared String variable named "name". Then, a line of input is taken from the user through the ReadLine() method of the Console class. The result is stored in the "name" variable. The variables are placeholders (in memory) for storing data temporarily during the execution of the program. Variables can hold different types of data depending on their data-type, e.g., Integer variables can store integers (numbers with no decimal places), while String variables can store strings ( a series) of characters. The ReadLine() method of the Console class (contrary to WriteLine()) reads a line of input typed at the Console Window. It returns this input as a string, in which the "name" variable is stored.
Author's Note: String is implicit data-type in VB.Net contrary to other languages
The third line prints the name given by the user at second line along with a greeting text. Once again, the WriteLine() method of the Console Class is used. The substitution parameter {0} is used to specify the position in the line of text where the data from the variable "name" should be written after the WriteLine() method is called.
When the compiler finds a substitution parameter {n} it replaces it with the (n+1) variable following the string in double quotation marks separated by comma. Hence, when the compiler finds {0}, it replaces it with (0+1), i.e., 1st variable "name" following the double quotes separated by comma. At run-time, the CLR will read it as:
If the value of the variable "name" = "Faraz" at run-time.
Alternatively, it can also be written as:
Removing the substitution parameter altogether. Here we concatenate (add) the strings together to form a message. (The first approach is similar to C's printf() function while the second is similar to Java's System.out.println() method)
When we compile and run this program the output will be as follows:
"Plz, write your good name: Faraz Hello Faraz, Good Luck in VB.Net"
As follows, we will build our first VB.Net application without and then with Visual Studio.Net. Instructions below show, how to write, compile, and execute a VB.Net application.
Without Visual Studio.Net
Open "Notepad" or a text editor of your choice and type the following code:
Code:
Imports System
Module Module1
Sub Main()
Console.WriteLine("Hello World!")
End Sub
End Module
Code:
vbc MyFirstApplication.vb
This will compile your program and create an .exe file (MyFirstApplication.exe) in the same directory. Errors will be reported if there are any. To run your program, type:
Code:
MyFirstApplication
This action will print "Hello World!" on the console screen.
With Visual Studio.Net
Start Microsoft Visual Studio.Net and from the menu select File > New > Project. A "New Project" dialog will now be displayed. Select "Visual Basic Project" from "Project Type" and select "Console Application" from "Templates". Type "MyHelloWorldApplication" (without "") in the "Name" text box below, then click OK.
Change the name of module from Module1 to "MyHelloWorldApplication" and type
Code:
Module MyHelloWorldApplication
Sub Main()
Console.WriteLine("Hello World")
End Sub
End Module
Let's build on this code and include some more VB.NET syntax. Modify your code as below:
Code:
Imports System
Namespace MyHelloWorldApplication
Module MyHelloWorldModule
Sub Main()
Console.WriteLine("Hello World")
End Sub
End Module
End Namespace
The first line of our program (Imports System) usually appears in all VB.Net programs. It gives us access to the core functionality of programming. This shall be covered later. Before then, the second line (Namespace MyHelloWorldApplication) shall be discussed.
Namespaces in VB.Net
A namespace is simply a logical collection of related classes in VB.Net. We bundle our related classes (like those related with database activity for example) in a named collection, hence calling it a namespace (e.g., DataActivity).
VB.Net does not allow two classes with the same name to be used in a program. The sole purpose of using namespaces is to prevent the name conflict, which may happen if your working with a large number of classes. It is the same case in the Framework Class Library (FCL). It is highly possible that the Connection Class in DataActivity conflicts with the Connection Class of InternetActivity. To avoid this, these classes are made part of their respective namespace. The fully qualified name of these classes will be DataActivity.Connection and InternetActivity.Connection, hence resolving any ambiguity for the compiler.
In the second line of the code there is a declaration classes (enclosed in Namespace...EndNamespace block) which are part of the MyHelloWorldApplication namespace.
Code:
Namespace MyHelloWorldApplication ... End Namespace
Code:
Namespace Parent Namespace Child ... End Namespace End Namespace
The first line of our program is
Code:
Imports System
Code:
Imports System.Collections
The Module Keyword
A VB.Net program may contain one or more modules. The Main() sub-procedure usually resides in one of these modules. Modules in VB.Net are a combination of general data (fields) and general functions (methods) that are accessible to any code that can access the namespace of a module. All the members (fields, methods, properties) defined inside a module are shared by default.
The concept of a Module will be discussed in more detail in future lessons. Modules in VB.Net are defined using the Module statement, followed by the name of the module. The end of a module is marked with the End Module statement.
Code:
Module MyHelloWorldModule
...
End Module
Code:
Imports System
Code:
Namespace MyHelloWorldApplication
Class MyHelloWorldClass
Public Shared Sub Main()
Console.WriteLine("Hello World")
End Sub
End Class
End Namespace
One interesting point is that it is legitimate to have multiple Main() methods in VB.Net program. However, you have to explicitly identify which Main method is the entry point for the program.
Printing on the Console
The next line of code prints "Hello World" on the Console screen:
Code:
Console.WriteLine("Hello World")
VB.Net, like other Object Oriented languages, uses the dot (.) operator to access the member variables (fields) and methods of a class. Also, parenthatsis () are used to identify methods in the code. String literals are enclosed in double quotation marks ("). Lastly, it must be remembered that VB.Net is a case-insensitive language; hence Console and conSole are the same words (identifiers) in VB.Net.
Comments
Comments are created by programmers who wish to explain the code. Comments are ignored by the compiler and are not included in the executable code. VB.Net uses similar syntax for comments as used in VB and assembly language. The text following a single quotation mark (' any comment) is a line comment. the ending is the end of the line.
Code:
' This is my main method
Public Shared Sub Main()
Console.WriteLine("Hello World") ' It will print Hello World
End Sub
- Your VB.Net executable program resides in a class or module.
- The entry point to a program is the Shared sub-procedure Main()
- VB.Net is not a case sensitive language so integer and Integer mean the same thing
- Horizontal whitespaces (tabs and spaces) are ignored by the compiler between the code. Hence, the following is also a valid declaration of the Main() method (although not recommended):
Code:
Public Shared Sub Main()
Console.WriteLine ( "Hello World" )
[/ul] End Sub
- You DON'T need to save your program with the same file name as that of the class or module containing the Main() method
- There can be multiple Main() methods in your program, but you have to specify which one is the entry point
- The boundaries of a namespace, class, module and method are defined by their respective statements and closed with an End statement
- A namespace is only a logical collection of classes with no physical mapping on disk (unlike Java)
- The "Imports" keyword is used to inform the compiler where to look for the definition of the classes (namespaces) that you want to use
- Comments are ignored by the VB.Net compiler and are used only to enhance the readability and understandability of the program for developers only.
- Enclosing your classes or modules in a namespace is optional. Its possible to write a program where any classes or modules are not enclosed in a namespace
- It is not mandatory that the Main method of a program does not take any argument. It may take arguments, such as:
Code:
Public Sub Main(ByVal CmdArgs() As String)
Console.WriteLine("Hello World")
[/ul] End Sub
Up to this point we have seen a very static Hello World application that greets the whole world when it is executed. Lets now make a more interactive hello world that greets its current user. This program will ask the user's name and will greet them using their name, like 'Hello Faraz', when the user named 'Faraz' runs it. Let's see the code first:
Code:
Module MyHelloWorldModule
Sub Main()
Console.Write("Plz, write your good name: ") ' line 1
Dim name As String = Console.ReadLine() ' line 2
Console.WriteLine("Hello {0}, Good Luck in VB.Net", name) ' line 3
End Sub
End Module
In the first line of Main, there is another method, Write(). Which is part of the Console class. This is similar to the WriteLine() method discussed in the previous program, but the cursor does not move to a new line after printing the string on the console.
In the second line, there is a declared String variable named "name". Then, a line of input is taken from the user through the ReadLine() method of the Console class. The result is stored in the "name" variable. The variables are placeholders (in memory) for storing data temporarily during the execution of the program. Variables can hold different types of data depending on their data-type, e.g., Integer variables can store integers (numbers with no decimal places), while String variables can store strings ( a series) of characters. The ReadLine() method of the Console class (contrary to WriteLine()) reads a line of input typed at the Console Window. It returns this input as a string, in which the "name" variable is stored.
Author's Note: String is implicit data-type in VB.Net contrary to other languages
The third line prints the name given by the user at second line along with a greeting text. Once again, the WriteLine() method of the Console Class is used. The substitution parameter {0} is used to specify the position in the line of text where the data from the variable "name" should be written after the WriteLine() method is called.
Code:
Console.WriteLine("Hello {0}, Good Luck in VB.Net", name);
Code:
Console.WriteLine("Hello Faraz, Good Luck in VB.Net");
Alternatively, it can also be written as:
Code:
Console.WriteLine("Hello " + name + ", Good Luck in VB.Net");
When we compile and run this program the output will be as follows:
"Plz, write your good name: Faraz Hello Faraz, Good Luck in VB.Net"
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:
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:
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.,
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
Rather, you would have to write,
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
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:
Constants must be initialized as they are declared.
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
Some typical names of method following Pascal Notation are
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:
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
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
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.
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
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
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.
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
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
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
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:
Logical Operators And, Or, AndAlso and OrElse are also used to combine comparisons like
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:
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
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:
The Else clause above is optional. The typical example is
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.
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.
You may write If...Then or If...Then...Else in the single line, like
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
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:
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
Instead, you can either use
or
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:
It takes much less time to use the Select...Case than using several If...Then...ElseIf statements. Let's understand it with an example
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
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
If all the specific checks fail (input is neither 1,2,3,4 or 5), the statements under “Case Else” will execute.
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
* 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:
Lets see a For...Next loop that will write integers from 1 to 10 on the console
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:
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
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
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
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
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:
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
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:
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.
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:
Lets define an array of Integer type to hold 10 integers.
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:
You can optionally perform declaration and initialization in separate steps like below:
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
Lets make a program that uses an integral array.
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
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
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
Lets now make our previous code iterate through an array with a For Each loop
Simple and more readable! Isn't it?
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.
This will print each character of the name variable on a separate line.
Lesson #3 coming soon!
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' |
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>
Code:
Dim i As Integer
Code:
Dim isReady As Boolean = True
Dim percentage = 87.88, average = 43.9 As Single
Dim digit As Char = "7"c
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,
Code:
Option Explicit On
Code:
myName = "Faraz" ' compile time error with Option Explicit On
Code:
Dim myName As String = "Faraz"
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
Code:
Option Strict On
Code:
Sub Main() Dim strNum As String = "1" Dim intNum As Integer = strNum Console.WriteLine(intNum) End Sub
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
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
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"
Code:
Dim myName As String = "My name is " & _ "Faraz Rasheed and, " & _ "I like .Net as ..." Console.WriteLine(myName)
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
Code:
Console.WriteLine("Sum of {0} and {1} is {2}", num1, num2, sum)
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
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
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)
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)
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
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
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
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
Code:
bool firstVar = (i>3 And j<10) OrElse (i<7 And j>10)
'firstVar would be true
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
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
Code:
If i=5 Then
Console.WriteLine("Thanks God, i finally becomes 5")
End If
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
Code:
If i=5 Then Console.WriteLine("Thanks God, I finally became 5")
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
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
Code:
Dim flag As Integer = 0 If flag Then ' do something... End If
Code:
Dim flag As Integer = 0 If flag = 1 Then ' note == ' do something… End If
Code:
Dim flag As Boolean = False If flag Then ' Boolean expression ' do something... End If
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
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")
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")
* 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
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
Code:
For i = 1 To 10
Exit For
Console.WriteLine()
Next
Code:
For i = 1 To 10 Step 2
Console.WriteLine("Value of i is {0}", i)
Next
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
Code:
Dim i As Integer =1
Do While i<=10
Console.WriteLine("In the loop, value of i is " & i)
i = i + 1
Loop
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
Code:
Dim i As Integer = 1
Do
Console.WriteLine("In the loop, value of i is " & i)
i = i + 1
Loop While i<=10
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
Code:
Dim i As Integer = 1
Do
Console.WriteLine("In the loop, value of i is " & i)
i = i + 1
Loop Until i=10
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>
Code:
Dim myIntegers(9) As Integer
Code:
Dim size As Integer = 10 Dim myIntegers(10-1) As Integer
Code:
Dim myIntegers() As Integer
myIntegers = New Integer() {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)
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
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 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
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
Code:
For Each i in myIntegers
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
Lesson #3 coming soon!