For the first lines of code in Visual basic, I have decided to create a simple console application like the one we created in the previous tutorials. We are going to explore what each line is doing from the code below. Double click on the Program.vb in solution explorer, then you will write the following :
Module Program Sub Main() 'Writes into the console Console.WriteLine("Hello all!") End Sub End Module
It is really important to always know what the computer is doing with the code we write. The computer has no brain, you have one so you need to tell it exactly what to do.
Here Program.vb will be the first file the computer is going to access when we will hit Start. It will navigate line by line and enter the Main().
What is Main()? It is most of the time refered to as the entry point of the software, that is, the first thing that gets executed.
You can now try and run this thing! Hit Start in the Top toolbar. What is going on? If everything ran smoothly, you should have seen a black window appear and disappear instantly.
This is because the computer ran your code and then exited the program. We will have to tell it to stop so we can make sure that what is being displayed is really what we want – “Hello all!”.
As you can probably figure out, Console is a component that we are using to control the Console itself. In that case, WriteLine is telling the Console to Write a line. What is going between the parenthesis is what to write. In our case “Hello all!”.
Why do we put “” then?
We have to tell Visual Basic that what we give to WriteLine is a character string or if you prefer, a sentence containing multiple characters. “I am a sentence containing multiple characters :)”.
'In the end it gives us the line :
Console.WriteLine("Whatever you want to write!")
This is the core of the code, but what is with all the rest?
Lets just say that Module is a piece of the software for now and that a Sub is like a functionality, in that case, the first functionality the computer is going to execute.
'Add this line to the code
Note that the ReadKey method does not take a character string between the parenthesis. This is logical too because what we want to do now is to Read a Key into the Console. Whatever key the user is going to click there will be read by the Console and recorded.
Now try to Start the code again. What is going on now?
That’s it! The Console is waiting for us to click on a key to continue its processing!
It was easy wasn’t it?! You should try changing the Console.ReadKey() for Console.ReadLine() and see what happens.