Page 1 of 1

Programming Fundamentals - Part 2 Rate Topic: ***** 1 Votes

#1 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 2890
  • View blog
  • Posts: 9,597
  • Joined: 12-December 12

Posted 08 July 2013 - 04:46 AM


In this tutorial I will guide you through the fundamentals of VB.NET. In fact, the following topics are fundamental to every programming language. You cannot make progress without an understanding of these topics.

Part 1
  • Adding Comments
  • Basic input/output - Using the Console
  • Creating and Using Variables
  • Arithmetic Operators
  • Option Strict On (VB.NET specific)
  • Manipulating Strings
  • Conditional Structures (If)

Part 1 is here

Part 2
  • Looping Structures
  • Custom and Built-in Functions
  • Introducing Arrays
  • Introducing Lists

I won't be discussing OOP (object-oriented programming), WinForms, WPF or any other technology. Just the fundamentals of programming! We will run our code as a Console Application. The Console is very useful to help us learn programming concepts, without the distraction of a pretty form. In reality, very few applications are built as a Console Application. (Occasionally, some system tools are.)

This tutorial can only provide an introduction to VB.NET programming. It cannot be a substitute for a full tutorial or a book. I need to foreshorten a number of topics, unfortunately, but I do provide links to relevant MSDN pages for further study.

Visual Basic Resource :MSDN

Looping Structures

Loop Structures :MSDN

While..End While, Do..Loop, For..Next, For..Each

Posted Image

Computers, and Computer Programming, are built around three central ideas: Variables, Branching and Looping. We need variables (memory locations) to store input, branching to make decisions (based on these values - the input), and looping to repeat statements until a certain condition is met; that is, until a variable contains a certain value.

Run the following code to demonstrate the Do..Loop. It asks the user to supply the correct password, but only allows them three attempts.


The Do..Loop will execute the statements between the words Do and Loop, until a certain condition is met (or while a certain condition applies).

Microsoft provides Naming Guidelines for naming your identifiers. You should read this and try to follow the guidelines as much as possible. However, I am old-school and I like to name my String (local) variables with a prefix 's', and Integers with 'i'. You will find many discussions (debates) on this topic if you search the internet. More important than the conventions, though, is that you are consistent in your naming. (My earlier code didn't include these prefixes as I didn't want to introduce them too early.)

I have named a variable x. When using a variable to simply count - a counter variable, sometimes called a sentinel - it was traditional in earlier versions of Visual Basic to use x and y (and z if necessary). You will also find this very common with VBA (Visual Basic for Applications) in Excel. Nearly every other language uses i, j (and k), and a lot of examples you will find in VB.NET have adopted this convention. It is not important. Every other variable you should give a meaningfulName.

The String variable sAttempt could have been set equal to "", and often is. I am encouraging the more OOP way to code. String is a Class and Empty is a field of this Class. [Actually, it is the only field of the String Class.] We should use the more modern OOP-coding practices wherever possible. (At some point you are likely to work with C# or another OOP programming language, and doing so will ease the transition.) There is an MSDN link for OOP provided at the end of this tutorial.

Similarly, I could have used If sAttempt = "" Then and If sAttempt = sPassword.

VB.NET is an object-oriented programming language. However, because of its history, there are a number of features, and functions, that have been retained from earlier versions that don't occur in other OOP languages. However, this mainly concerns people like myself who are familiar with the earlier versions.

Console.Write("Attempt {0}: ", (x + 1))

This is an alternative, and more flexible, way of printing to the console, rather than using & to concatenate (join) text. {0} will be replaced with the first value that follows the comma. {1} would be used if there were a second value after the comma. Note that we no longer need to use ToString as the format item {0} automatically inserts the string representation of the value.

Composite Formatting :MSDN

    x = x + 1       'increment the counter variable
    bCorrect = (sAttempt.Equals(sPassword))

This first statement is incrementing. Whatever value x currently contains (initially 0), add 1 to it, and store this as the new value of x. 1,2,3,4,5,.. and onwards. This can also be written as:

x += 1

Assignment Operators

The second statement sets the Boolean (True/False) variable bCorrect to whatever is the result of the expression sAttempt.Equals(sPassword). Equals() will return a Boolean result of either True or False. (The outer brackets aren't required, but I felt the statement looked clearer with them.)

I could have replaced the keyword Until with While:

Loop While x < 3 And sAttempt <> sPassword

<> means "is not equal to". The two statements are logically equivalent, it is up to you to decide which version makes most sense with your code.

I shall omit While..End While. Please read the documentation here. It is quite similar to Do..Loop.

The For..Next looping structure is generally used in preference to the Do..Loop when we have a clearer idea at the outset as to how many times we will need to repeat a loop. For x = 1 To 10 says, essentially, "do the following 10 times". Here is a very common, but not very exciting, example:


Rather than simply writing to the console, though, within the loop we might read 10 lines of text from a file, or examine 10 rows of data from a database. For..Next loops are often nested (using another variable 'y'), allowing us to navigate through a table, or matrix, of some kind.

Did you notice that the value of x after the loop completes is 11? VB will keep increasing the value, checking it as it returns to the top of the loop. When the value is 10 it can continue through the loop. It is then increased to 11 and, at that point, it knows that the looping is complete. This is a very common trap. Counter variables (x, y, i, j) don't have a meaningful name and we should ONLY use them to control the number of loops that are executed. We should not make any assumption about their value outside of a loop.

The For..Each loop is used to loop through each element of a collection. There are many collections that you will encounter with VB.NET. For the following example we loop through the collection of characters in a String.

        Dim sMyName As String = "Andrew"

        Console.WriteLine("Looping through a 'collection' of letters:")
        For Each lett As Char In sMyName
            Console.Write("{0}, ", lett)

Char is another data-type, storing a single character. You would assign a single character using double-quotes followed by the letter c:

Dim cEnd As Char = "z"c

Custom and Built-in Functions

Type the following function after the End Sub (of Main()) but before the closing End Module.

    Function DoubleIt(ByVal iTheParameter As Integer) As Integer
        Return (iTheParameter * 2)
    End Function

Enter the following, which uses our function, back in the (Main()) Sub and run the application.

        Console.WriteLine("Doubling {0} we get {1}", 10, DoubleIt(10))
        'Doubling 10 we get 20

Within the brackets of the function we list its parameters separated by commas. For our example there is only one parameter. ByVal says that our function will not alter the original value. ByRef is the alternative. They are called modifiers.

The data-type specified after the closing bracket determines what type of value the function will return.

Functions may consist of many lines of code, but at some point they need to return a value using the Return statement.

Function Statement :MSDN

When we use a function, the values that we supply are called 'arguments'. When we refer to the function definition we call these the function's 'parameters'. However, you will often see these terms used as synonyms. If it helps you can think of arguments as the values that you "actually supply", but it is not a big deal if you mix these terms.

VB.NET has many built-in functions that we can use. They are listed here in various categories. Have a look through to familiarize yourself but, typically, you will pick them up as you need them.

These built-in functions were inherited from the previous version of VB.NET, VB6. Most of them have more modern OOP equivalents. For example, the LCase() function is equivalent to the String Class's ToLower() method. You should use the modern OOP versions in preference, but some of the functions remain very useful, particularly some of the type conversion ones like CInt() and Val().

Introducing Arrays

Arrays in Visual Basic :MSDN

An array allows us to store a number of values of the same type. We can use a For..Next or For..Each structure to loop through all the elements of the array. Explore the following code.


Arrays are indexed from 0. That is, we refer to the first item as arrayName(0). When we declare an array as Dim arrayName(5) the number five is the upper-bound, the last index of the array. So there are actually six elements, indexed from (0) to (5). Adding and attempting to run the following

Console.WriteLine("{0}", sBooze(4))

will produce one of the most common errors:


System.IndexOutOfRangeException was unhandled

We are attempting to refer to the FIFTH element of the array, but there are only 4 - indexed from 0 to 3.

Arrays are most useful when we know at the outset how many values we need to store. The UK lottery only allows us to select six number, and there are 64 squares on a chessboard.

Significantly, we cannot add additional elements to an array, or remove existing elements (reducing the size of the array). We can set, for example, an element of an Integer array to 0 but this does not remove the element.
(This is not exactly true. We can create a dynamic array. A List is a much better option. Search the previous Arrays link for the word ReDim if you want to investigate dynamic arrays. For the more modern equivalent search zero-length or empty arrays which don't use ReDim.)

If you don't know exactly what size of array you need, you might consider creating a very large array and ignoring those elements you won't use. This is messy and inefficient. Consider a List instead, discussed next.

If you are faced with the choice between using an Array or a List always favour a List.

Introducing Lists

List(Of T) Class :MSDN

A List is a very flexible alternative to an Array. We can add as many items as we want to a List, remove items, sort them, etc.. (Arrays can be sorted, but we cannot add or remove elements.) Type and run this code:


Notice that our List is instantiated with the New keyword. A List is a Class and needs to be instantiated before we can use it. Using Dim sShopping As List(Of String) would initially be accepted in Visual Studio. However, this only says that sShopping will refer to a List.., it doesn't yet have a List to refer to. Try running the code without the word New and you will receive the most popular error that we encounter on forums:


System.NullReferenceException was unhandled

(well, this is perhaps a close second behind 'IndexOutOfRangeException' - see the Arrays section above)

When we include the New keyword in the declaration (the Dim statement) we are saying "create a new List (of strings) and point sShopping at this List". Alternatively, you could declare and instantiate on separate lines:


This was previously the recommended practice because, if an error occurs, you will be taken to either the declaration, or the instantiating, line. However, Visual Studio has an extremely good error reporting system, so this is less of a concern than it used to be. Nevertheless, you might want to use two lines until you gain more confidence with VB.NET.

A List is the most commonly used Collection in VB.NET, but there are many others. System.Collections.Generic :MSDN

I must stress that this tutorial has only scratched the surface of VB.NET. You need to continue your studies and, once you are confident with the concepts I have introduced here, move on to Object Oriented Programming. BTW I am not recommending that link as your first OOP tutorial, it is more for reference. Have a look through the Tutorials here @DIC.

Before tackling OOP, though, you should read up on Exception Handling.

This post has been edited by andrewsw: 12 August 2013 - 04:09 PM

Is This A Good Question/Topic? 8
  • +

Page 1 of 1