- 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)
- Looping Structures
- Custom and Built-in Functions
- Introducing Arrays
- Introducing Lists
Part 2 is here
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
Start Visual Studio (doesn't matter which version) and start a new VB.NET Project, choose Console Application. Give it a name (I used 'Console1vb'). The IDE (integrated development environment - Visual Studio) generates code like this as your starting point:
Module Module1 Sub Main() 'I can type anything I want after an apostrophe! End Sub End Module
Type the line beginning 'I can type... Do not just copy and paste the code. You need to be involved in the programming process, to make mistakes and discover how to fix them. Copying and pasting code won't help you.
I've added the line beginning with an apostrophe. As soon as we type an apostrophe we are creating a comment (our own notes) and the text will be green by default. Writing meaningful, and useful, comments is an important skill and you should get in the habit of commenting your code at an early stage.
Comments should provide additional details to help someone reading your code understand what the code is doing. (This someone might be yourself in a few weeks time!)
Initially you should write lots of comments. As you gain more experience, and hopefully write very nice, clear code, you will find that you need to provide fewer comments. But please don't fall into the habit of not commenting.
Basic input/output - Using the Console
Modify the code to the following. As we go through the tutorial you can continue to add code to the same Console Application. You'll probably want to comment out previous lines - once you've understood them - by inserting apostrophes at the beginning of each line. Alternatively, at certain points you might decide to start a new Console Application. I suggest also that you copy the code-lines into a text-file as you proceed. This way, you can start to create your own notes.
Module Module1 Sub Main() 'I can type anything a want (a comment) after an apostrophe! Console.WriteLine("Hello World!") Console.ReadKey() End Sub End Module
The traditional example! Choose the File menu, Save (or Save All if you prefer) and click the green arrow on the main toolbar to Start Debugging (I call this the 'Run' button). You can press the F5 function key if you prefer. The Console should appear with the text "Hello World!". It will remain open until you press a key on the keyboard.
Sub stands for sub-procedure. When we run a console application, VB will look for a sub-procedure named Main() and execute the code that it contains. Most of the time, however, we use the more general term procedure. Our code is also contained in a Module, but this won't be important during this tutorial.
If there are errors then the code won't run and error messages will appear in the Output Window at the bottom of the screen. Visual Studio (VS) will also take you to the first line that generated an error. Check for any spelling errors, correct them, and run the application again. As you type, VS will also underline potential errors, and provide warnings. When you see any coloured underline, or other symbols, point your mouse over this indicator and a message will often pop-up.
At an early stage you will want to read my Debugging Express tutorial. Learning to debug and step-through your code is an essential skill.
Console.ReadKey() is necessary, otherwise the console will just appear and close very quickly. .Read() or .ReadLine() will have a similar effect but I tend to go with ReadKey.
VB.NET is not case-sensitive, so it will accept console.writeline() as well but will capitalize the words for us. I tend to type in lower-case and let VS adjust this for me. I encourage you to do the same. If the word doesn't capitalize then this is a very good visual clue that you have misspelt it. Bear in mind, though, that almost every other language IS case-sensitive.
Try deleting the parentheses after .ReadKey, VS will re-insert them when you click away from the line. Sometimes, however, it doesn't insert them - but the code still works! VB.NET is very tolerant about missing parentheses. Personally, I am not fond of this feature; I would rather it gave me an error and insisted I insert them. Generally, I don't type empty parentheses () and I let VS insert them if it wants to.
Console.WriteLine() writes a complete line to the console, moving the cursor to the next line (technically, inserting a newline character). .Write() keeps the cursor on the same line. Add these additional lines (before the ReadKey() line) and run the application (F5):
Console.Write("One ") Console.Write("Two ") Console.Write("Three ")
Select these three lines. You can then comment them out in one go by pressing a button on the main toolbar ("Comment out the selected lines.") or use Ctrl-K, Ctrl-C. Ctrl-K, Ctrl-U will uncomment lines.
Creating and Using Variables
Writing to the console is good, but we also want to interact with our user, letting them type something in return. We have Console.ReadLine(). Although we can execute this statement it is pretty useless on its own. Yes, the user can type something, but this can hardly be called 'interaction'. We need some way to examine what they have typed. We need to store their text somewhere, to be able to check what this text is, and do something depending on what they have typed.
We store values in variables. A variable is a place in the computer's memory that can store a value. The value might be text, a number, a date. This is called the variable's data-type. When we create a variable we give it a name that we can later use to examine, or change, the stored value.
Give variables a meaningful name such as firstName. Use camelCase for variables: the first letter is in lowercase, subsequent words begin with a capital. Another example: fullPostAddress. We can use letters, numbers and underscores in the name but it cannot start with a number.
Add and run the following code; again, inserting it before the ReadKey() line.
'Declare a variable named 'firstName' to store some text Dim firstName As String Console.Write("What is your first name? : ") 'store what the user types into this variable firstName = Console.ReadLine() ' an assignment statement Console.WriteLine("Good morning " & firstName)
The word Dim stands for Dimension, but this isn't very helpful. I prefer to think of it as meaning Create. "Create a variable named 'firstName'". As String tells the compiler what type of value we will store in the variable. That is, the variable's data-type is String. String means text.
We store a value in a variable by setting it equal to something. That is, we assign a value to the variable using an assignment statement. In this example, we are storing whatever the user has typed in the console.
The ampersand (&) is called the concatenation operator. We use it to join pieces of text together. Always put spaces either side of the ampersand. (There is a technical reason why not doing so may cause an issue, but if you always add the spaces then you won't need to worry about this.)
Add the following lines and run the application:
These additional lines don't produce any output, they just demonstrate some different data-types, and how we might assign them suitable values. There are many other data-types: Data Type Summary :MSDN. Our code demonstrates the ones you are, initially, most likely to use.
Far and away the most commonly used data-types are Integer and String. An Integer is a whole number (no decimals) ranging between -2,147,483,648 and 2,147,483,647 (without the commas!). A String can store "between 0 to approximately 2 billion Unicode characters", although I would never attempt to store anything like this number of characters in a single string.
The Boolean data-type is the simplest. It can only store a value of either True or False.
DateTime is actually a Structure and Today() is a property of this structure that we can use to obtain today's date. DateTime :MSDN. I won't go into details here though, as I want to keep this tutorial to a reasonable length.
The 'lucky' variable has been both declared, and initialized (given an initial value), at once. Variables that are not initialized in this way will still have a default value. For integers this is the number 0, for a string the empty string value "", for Boolean the value False.
Add and run the following code, which demonstrates the basic arithmetic operators.
The WriteLine() method expects to write text (a string), so each time we use the ToString method to convert the numbers to text.
Although this code demonstrates some basic arithmetic you should study this MSDN page for further details. This is an important topic but a little too extensive for this short tutorial. This zetcode page is reasonable. It uses the Byte data-type in the examples, which is a small Integer ranging from 0 to 255. tutorialspoint also has a useful summary page.
From the previous MSDN linked-page:
Option Strict On
Add and run the following two additional lines.
iResult = first / second Console.WriteLine("Implicit Integer division: " & iResult.ToString)
The result is 4, the number of times 24 can (completely) fit into 100. Now go to the very top of your code and add the statement Option Strict On before Module Module1. If you attempt to run the code now VS will produce the error:
Option Strict Statement
Essentially, with Option Strict On, VB.NET will not automatically convert one data-type to another, if that other type stores a smaller range of values. Dividing two numbers results in a Double, which has a larger range than the Integer variable that we are using to store the result.
I strongly recommend that you always include Option Strict On at the top of your code. It will help you discover hard-to-find errors, it will help you understand how different data-types work, it will make you a better programmer.
You can set this On permanently from the Tools menu, Options, Projects and Solutions, VB Defaults. You can also set it per project from the Project menu, Project Properties.
There should be a little marker at the end of this line: iResult = first / second. Point your mouse over the word 'second', click on the button that appears, and VS offers to
Accept (click) this option and you will be able to run the code. Leave Option Strict On at the top of your code.
CInt() is a VB.NET type conversion function. There are many of these: CDbl, CStr, etc. Converting types is an important topic. Search MSDN for Convert, Parse and TryParse.
Add and run the following code. You may still have 'firstName' declared earlier in the code; if so you can remove the first code-line.
We are using a number of methods of the String Class. The String Class is the largest of the built-in types, it has the most methods and properties (collectively called its members).
Manipulating strings is extremely important to understand. Understanding Substring in particular is, perhaps, the key to understanding strings. someStringVariable.Substring(2, 4) will return 4 characters starting with the THIRD character. The characters of a string (and any other collection for that matter) are counted (indexed) starting from 0, NOT from 1. The first character of a string is at position 0.
Also called Decision or Control of Flow structures.
The If Structure is.. well, essential, fundamental. It is the sine qua non of all computing. Without the ability to make decisions, to be able to produce different output for different input, computers would be no more useful than a hole-punch, or a ticket-dispenser.
Run the following code which demonstrates the syntax of the If structure. syntax (wiki): "In computer science, the syntax of a computer language is the set of rules that defines the combinations of symbols that are considered to be correctly structured document or fragment in that language."
< is a Comparison Operator meaning 'less than'.
- The console always returns a String, so we use CInt() to convert this to an Integer. We shouldn't really do this though. We should first store the string in a (string) variable, then check to see if it can be converted to an integer.
- Notice that the If, and each ElseIf, line ends with the keyword Then.
- ElseIf is one word.
- There can be only one Else clause, which must be the last one, but it is optional.
- The If structure is completed with End If.
Each branch (each clause) only contains a single (Console.WriteLine) statement. However, there could be many statements. If you have too many statements within a particular branch then it is advisable to create a Sub (or Function) procedure that you can call within the branch. The decision as to what constitutes too many lines is up to you. Someone suggested that if a block of code cannot fit on-screen then it is too long. This may be a bit too strict but I like it as a rule of thumb.
Select..Case is a useful alternative to If..Then, when the different branches depend on a value. The following is an alternative to the previous example.
The test expression (age in this instance) must "evaluate to one of the elementary data types (Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort)".
Go to Part 2
This post has been edited by andrewsw: 15 August 2013 - 01:53 PM