Getting Started with VB.NET | The Complete Basics Part 1

View previous topic View next topic Go down

Getting Started with VB.NET | The Complete Basics Part 1

Post by Admin on Sat Mar 11, 2017 7:43 pm

Getting Started
Before we begin, lets talk a little bit about the .NET framework itself. Microsoft has developed it over the course of ~13 years (1.0) and built a powerful powerful programming library known as the .NET framework. This library covers such a wide spectrum of programming it accelerates the software development process - not to be confused with RAD - greatly which explains why it's so competitive against native languages such as most of the C family since it's so easy to produce an application.

We'll need an Integrated Development Environment (IDE) to get started. An IDE is an environment to develop software in. Core features include a code editor, compiler, and debugger, along with a designer for easy GUI creation. In other words, a program that creates programs. The most popular IDE for .NET and other language development is Visual Studio which is developed by Microsoft and we'll be using it for this tutorial. You can find a download to Visual Studio 2015 Community edition here. Installation may take some time, especially if you have none of the prerequisites already.

Taking a Look Around
Don't worry if the interface looks daunting, there's a lot of new stuff to taken in and we certainly won't be using everything. Lets have a look at the main menus, toolbars, and windows.
You should see something like this (Click to View)

To expose the main windows and get rid of this start page, dive right in and create a new project by hitting "New project...".
This dialog window will show (Click to View)

An important tip: never follow 'WindowsApplicationX', it'll get confusing very quickly. For this demonstration, lets name is 'VBConsole'. Scroll to Visual Basic on the left tree view, then select Console Application. Hit Okay and Visual Studio (VS hereon) will create our project.
Once ready, our window should look like this (Click to View)

Here's a quick breakdown of what we see here:

  • Code editor (center)

    • Our main editor. Think of it as a giant notepad or word document.


  • Solution explorer (top right)

    • Shows all elements of our project (well, collection of projects)


  • Building (top toolbar)

    • Toolbar for setting the build mode, CPU targeting, and the big awesome Start button.


  • Properties (bottom right)

    • Side menu that allows us to view and edit properties of controls. We'll get to this later.




Now we'll study the code VS has given us automatically:
Code:
Code:
Module Module1



    Sub Main()



    End Sub



End Module

  • Module

    • Can be thought of as a code file, modules house any number of methods and classes.


  • Sub Main

    • Sub (sub procedure) Main (name) is our entry point and is the first procedure called when our application is loaded. We write in this method.




One of the best habits you can get into when working with VB is to write with Option Strict on. It not only prevents a lot of bad habits VB gained a bad reputation for which isn't good if you plan to move on to other languages, but it prevents some unexpected data which can throw up errors when we attempt to use it. To do this, declare:
Code:
Code:
Option Strict On
At the very top of your code editor, above the Module declaration.

Ready to Code?
I know you are! Have you ever heard of "hello world"? It's a very old tradition used to assess how intricate it was to simply print something out in a language and to test everything's working correctly. Most commonly, it's a newbie programmer's very first app. So let's try it out.

Fill your Sub Main method body with this line:
Code:
Code:
Console.WriteLine("Hello world!")

Hit Start and take it for a spin. Something unexpected happen? It just randomly closed? Excellent, this is what we should expect. The application has executed all of our instructions, there's nothing left to do but pack up and wave goodbye. Many languages can be thought of as working on a line-basis, although it's not entirely true, for now for us, it is.

Time to add one more instruction:
Code:
Code:
Console.ReadLine()

Take 2.

The ReadLine method we just called is waiting for some kind of input. As such, you can press enter to terminate.

Now we'll dissect what we see here:


Console exposes the .NET framework's Console class (System.Console) so we can access its members. This is a crucial part of object-orientation which we'll talk about later. The period/full stop can be thought of as a hierarchical delimiter. We're going down the branch of the class we just called. WriteLine is a sub procedure we just accessed. The Microsoft Developer Network (MSDN hereon) documents description:
Quote: wrote:Writes the specified data, followed by the current line terminator, to the standard output stream.

So we're writing our specified string variable ("Hello world!") followed by a line break to the console. We've specified this as an argument within the parenthesis of the method. Make sense so far? Don't worry if it doesn't, there's a reason some of this paragraph was bold.

Another thing to notice is how lovely and colorful our code editor is. This is what's known as syntax highlighting which colorizes certain parts of our code to make it far easier on the eyes and to recognize what's what just from the colors.

But syntax highlighting isn't the only tool we have to help us understand what's going on when revisiting code. We can also comment our code as a way of inline-documenting. We can document with the apostrophe mark. Like so:
Code:
Code:
Console.WriteLine("Hello world!") 'Write hello world to the console

Which, in our IDE, looks like this (Click to View)

You'll notice it's showing as green. It doesn't matter if you write actual code or an entire novel, commented lines won't be recognized as instructions.

Variables
Before we go any further, we need to look at one of the absolute fundamentals of programming: variables.

A variable stores information as an alias that can vary, but is of a certain type. We can manipulate a variable in so many ways. A very textbook description, so breaking it down with an example... We declare a local variable in VB like this:
Code:
Code:
Dim <name> As <type> = <value>

  • Dim

    • Short for declare-in-memory or 'dimension', declares we wish to create a variable.


  • <name>

    • Our variable's name which we will use to reference it throughout our program.


  • As

    • The identifier for our type to follow.


  • <type>

    • Kind(type) of value the variable will hold.


  • Equals (=)

    • This operator initializes this variable with the value on the right.




Think about your username here on HF, did the forum know what it was going to be? Nope. Did it know you were doing to have a username? Yep.

A review of core data types (Click to View)

Now, hide the above and collapse the following and guess the type of each value:

Spoiler (Click to View)

Let's put this new knowledge into practice. Head back to your console application. Remember ReadLine which we used to await input for our program to close? We can use that input. Let's try.

Code:
Code:
Sub Main()

    Console.WriteLine("Enter your name:")



    Dim name As String = Console.ReadLine()

End Sub

We've just read the user's input into memory. It's ours now to do what we wish. Any ideas what to do with it? Let's fire it right back at them.
Code:
Code:
Console.WriteLine("Hello " & name)

That ampersand (&) operator will join 2 strings together, known as concatenation. It's how we can build dynamic strings using data we don't know. Think back to what I said about your forum username. Check the top left corner and it reads: "Welcome back, <username>". It knows to welcome the user, but it doesn't know the user. Although it's a string, we wouldn't do something like:
Code:
Code:
("Welcome back, " & "name")

We wrap predefined - known as hard values - in quotes, but variables must be accessed by their alias explicitly. Don't forget we need to see what it printed, await input before closing!

For things we've already covered, I'll describe them but not provide immediately visible code. If you're struggling, collapse spoilers and see how it's done.

Time to start working with more than strings. Let's feed our console an Integer.
Declare a variable named 'age' as type Integer and set its value to the line the console reads (Click to View)

Our ReadLine call is throwing up an error, as shown by the squiggly line drawn under it. To view the error, go to the toolbar and hit View -> Error List. It will read:
Quote: wrote:Option Strict On disallows implicit conversions from 'String' to 'Integer'.

Rightly so, we can't have the code accepting a String (which ReadLine returns) when we need an Integer. So how do we convert? By using the Convert class. Like so:

Code:
Code:
Dim inputAge As String = Console.ReadLine()

Dim age As Integer = Convert.ToInt32(inputAge)

Convert is our class, we're calling the ToInt32 method (Integer is the alias for the System.Int32 class), and the string inputAge which is given the value from use input is read through the console and passed for conversion. Our age variable will be set to the integer representation of our input.

Arithmetic
Mathematics is a huge part of programming. Whilst you don't necessarily need to be great at maths as the stigma suggests, the 4 main operations are definitely necessary. Programming isn't designed to be alien, you will recognize a lot of things from mathematics. Arithmetic is one of them.

Quick definitions:
Operand - Subjects of the operation e.g with 5+5=10, the 2x 5's are the operands
Operator - What is performed on the operands e.g with 5+5=10, we're running an addition operation

We have the following arithmetic operators:

  • +

    • Adds one operand to another


  • -

    • Subtracts one operand from another


  • /

    • Divides one operand into another and returns a DOUBLE


  • \

    • Divides one operand into another and returns an INTEGER


  • *

    • Multiplies one operand by another


  • ^

    • Raises one operand to the power of another


  • Mod

    • Short for Modulus - divides two operands and returns the remainder





Kids' stuff, right? Fundamentally, it doesn't get any more complex than that. Math and variables go together hand in hand, you'll find that a constant whenever you're programming. We don't need hard values. Example:

Code:
Code:
Dim width As Integer = 5

Dim height as Integer = 3



Dim perimeter As Integer = (width * 2) + (height * 2)

So we've calculated the perimeter of a rectangle using the formula - which we know - but with values which we don't know. All mathematical rules still apply in programming, including BOD/PEDMAS as you can see from above.

Logic & Conditional Statements
As data varies, we may need to run alternate courses depending on what we're working with. Logic is a huge part of programming in general, so we'll first take a look at the If statement. It is as follows:

Code:
Code:
If <condition> Then

    <true instructions>

Else

    <false instructions>

End If

Breaking it down:

  • <condition>

    • Our logical expression that must return a boolean state (true or false)


  • Then

    • Ends the evaluation line and begins our true condition block


  • Else

    • Separates the true condition block from the false condition block


  • End If

    • Terminates our If block





So, if the condition is met, the set of instructions in the true block (<true instructions>) will be executed, otherwise, if false (remember booleans?), the false block will be executed.

Let's try it out. Do you still have your code for the age input? If not, it's available here:
Spoiler (Click to View)

We're going to determine if the user is old enough to drive. Lets create a variable that cannot be changed, known as a Constant, to hold our minimum driving age. This can be achieved with the Const keyword:
Code:
Code:
Const minAge As Integer = 16

We've just replaced our Dim(ension) keyword with Const(ant) and ensured it won't be changed.

Place this declaration just above the inputAge variable, but not outside Sub Main, else the variable will be global - more on this later. We'll use an If statement to determine whether or not the user is able to drive depending on their input. We'll then write a result to the console. Like so:

Code:
Code:
If age > minAge Then

    Console.WriteLine("You are old enough to drive.")

Else

    Console.WriteLine("You are not old enough to drive yet.")

End If

See that angle bracket (>)? It's known as a comparison operator. It assesses if a numeric piece of data is greater in value than another, just like in mathematics. So what if you are 16 years old and meet the threshold? You're not greater than 16 and so it'll result in false. The range of comparison operators includes <, >, <= & >=, and =.
Can you guess which one we need? (Click to View)

Great job if you got that right. >= can be translated to "greater than or equal to", again identical to mathematical rules. Time to update our code. Replace the greater than operator with >=. There's also one extra which is <>, used as not equal to i.e the negation of =.

Now what if 2 conditions can trigger the same outcome? It would be silly to write another If to account for it, so there's an operator for it! Actually, there are a bunch known as logical & bitwise operators. They include:

  • Not

    • Negates a Boolean expression


  • Or

    • Will return true if 1+ of 2 expressions evaluates True


  • OrElse

    • Identical to Or, but a short-circuit evaluation. More below


  • And

    • Unlike Or, the And operator requires both expressions to evaluate True


  • AndAlso

    • Identical to And, but a short-circuit similar to OrElse





Not:
In an If block where we're evaluating for False, we might use:
Code:
Code:
If <condition> = False Then

    <instructions>

End If

Which works perfectly fine, but isn't exactly best practice. Which is why we have the Not operator:

Code:
Code:
If Not <condition> Then

    <instructions>

End If

The rule comes from C# where a double equals sign is used for getting the value and a single sign is used for setting the value.

Or:
With Or, we can require only 1 of 2 conditions to evaluate to True. Both may evaluate to True and it will still enter the true instruction block. However, if both evaluate to False, it will not. Example:

Code:
Code:
Dim number As Integer = 5



If number = 5 Or number = 1000 Then

    <instructions>

End If

Thanks to VB's plain-English syntax, you can clearly see the number can be either 5 or 1000 for the true block to be ran.

And:
Unlike Or, And demands both expressions evaluate to True. Example:

Code:
Code:
Dim age As Integer = 18



If age > 12 And age < 20 Then

    <instructions>

End If

So in this example we can see it will require them to be within 13-19, checking if the age is in the range of teenager.

AndAlso/OrElse:
These are known as short-circuit operators and are newer than their shorter counterparts. They will evaluate one expression at a time and will either continue to evaluate the next or exit from the If block, which saves a pointless evaluation.

They are used just like the others. For example:

Code:
Code:
Dim age As Integer = 1



If age < 4 AndAlso age > 80 Then



End If

So if they are younger than 4 years old, it makes no bother checking if they are over 80.

There's one other part to the If block: ElseIf. This is how we build multiple conditioned If statements. Like such:

Code:
Code:
If <condition1> Then

    <condition 1 true block>

ElseIf <condition2> Then

    <condition 2 true block>

End If

For example, we could have age > minAge in condition1, and then age < minAge if age is less than minAge, identical to else. We could also include a further Else block which would fire if age was bang on 16. These are both optional. No Else(If) condition is mandatory for a valid If statement.

The alternative of an If statement is a Switch-- or in VB's case: Select Case. The Switch statement is useful when testing against values or ranges and can be far simpler than a cluster of If's. Depending on variable density and depth, it may compile differently. But that's a whole other story. It looks like this:

Code:
Code:
Select Case <expression>

    Case <condition> <Is | To>

      <instructions>

    Case Else

      <instructions>

End Select

  • Select Case

    • Opening the Switch


  • <expression>

    • A potential result of the expression


  • Case <condition>

    • Expression to check against which doesn't have to evaluate to type Boolean like the If counterpart. Can be Integer, Char, String, Single, etc


  • Is

    • Used in conjunction with a comparison operator we spoke of earlier if we want restriction


  • To

    • When checking for ranges, To is used between a start and end range


  • Case Else

    • Identical as Else in If, will route to this block if no conditions are satisfied





For example, we can categorize an age:

Code:
Code:
Const age As Integer = 18



Select Case age

    Case 0 To 12

      Console.WriteLine("Child")

    Case 13 To 19

      Console.WriteLine("Teenager")

    Case Else

      Console.WriteLine("Adult")

End Select

As you can see, I've included the To keyword in this example as we're checking our age Integer against ranges. If they're 0 to 12, they're classed as a child, 13 to 19 prints as teenager and anything else (which must mean they're older than 19) would print they're an adult.

Collections
Now what if we want to calculate a set of ages en masse? Having age1, age2, age3, age4, etc etc will get messy very quickly. So we hold it in an array. There are many benefits to this other than tidiness. We can access the data through the same alias (variable name) followed by an index (position) for specifically which part of the array we're referring too. This also allows us to iterate through them with ease. Here's how we declare an array:

Code:
Code:
Dim ages(4) As Integer

Very similar to the variables we've covered, the new face is (3). What does this mean? We've just - in a way - declared the highest bounds (size) of the array, in this case 4. In computing, we start counting from 0. This means positions 0-4 are all available for use. Time to populate them.

We can access elements in the array through their index. For example:
Code:
Code:
Dim ages(4) As Integer



ages(0) = 16

ages(1) = 24

ages(2) = 12

ages(3) = 45

ages(4) = 8

The first position (0) of our ages array has been given data; a value of 16, so on and so forth. It can also be populated when we declare it on a single line, like so:
Code:
Code:
Dim ages() As Integer = {16, 24, 12, 45, 8}

Through explicit initialization, there's no need to specify the size. As such, it makes more sense to bolt the array parenthesis markers on the type rather on the alias:
Code:
Code:
Dim ages As Integer() = {16, 24, 12, 45, 8}

Arrays can be multi-dimensional a.k.a arrays of arrays, but this gets complicated very quickly and since we're covering only the basics, we'll ignore these for now.

Iterations
Iterations are used for the same reasons we have arrays (tidiness, ease of access, etc). We can repeat a set of instructions (code) several times, including specific data (parameters) to use each time we loop. There are 4 types of loops:

  1. For

    • Iterates on a counter (index) basis across a specific range


  • For Each

    • When we have no use for the index, we can use this as a cleaner option


  • Do While

    • Iterates as long as a condition is true


  • Do Until

    • Iterates until a condition is true





    The last 2 can be interchangeable depending on what you're trying to do.

    We'll start with the For loop. It looks like this:
    Code:
    Code:
    For <counter> As <type> = <start range> To <upper bound>

        <instructions>

    Next

    • <counter>

      • Our numeric variable that can be accessed (scoped) only within the For block


    • <type>

      • Data type of our numeric variable. Most commonly an Integer


    • <start range>

      • Value to initialize the counter with. Usually 0


    • <upper bound>

      • Upper bound of the counter. How many times the loop will effectively circle


    • <instructions>

      • Our code to be executed through each run of the loop


    • Next

      • Terminates the loop block i.e "next iteration"





    Shall we test it out? Write the loop with the counter alias as 'i' of type Integer and initialize with 0, we'll run to an upper bound of 5. Press enter Did you get it?
    Click here and see (Click to View)

    You'll also notice that the Next keyword was added for you with one line of spacing. Visual Studio has lots of tricks like this to help speed up programming.

    That space between the loop is for our instructions to be repeated a specified number of times. Write to the console: "Position at i: " followed by i's value.
    Collapse if you need help (Click to View)

    Now run, you should see this (Click to View)

    Two things I want to bring up before we continue. First, remember when I said in computing we start counting from 0? There's your proof. Integer i is at 0 running through 5. Secondly, i is of type Integer but it's been accepted as a String. Why? We're building (concatenating) a string using the ampersand (&) operator. It implicitly converts the operands (items to be concatenated) its concatenating to their string representations. Therefore there is no need to convert to String explicitly.

    So when else can we use the counter? Another possibility is when working with an array. Do you still have your age integer array?
    Collapse if not (Click to View)

    Instead of looping to the value of 5, loop to the array's length (age.Length). The Length property holds an integer that represents the total number of elements in an array, especially useful when we may not know the size if it's dynamically populated. Back with arrays, we said a position in the array can be accessed by the alias with an index parenthesized. Like so:
    Code:
    Code:
    ages(i)

    Let's print out: "Age: " with the age at Integer i (see above). Give it a go. You'll notice it crashed with the error: "Index was outside the bounds of the array".

    So our index has exceeded the last position in the array. Why? The value at Length is 5, there are 5 places in the array... Any ideas? We start counting from 0! So we've technically tried to access ages(6) which clearly isn't possible.

    If we tried to correct this by making i start from 1, it'll still throw the out of bounds exception. So we subtract 1 from the array's Length property.
    Collapse if you need help (Click to View)

    Base 0 will take some getting used to, that's why I littered it over the thread so far.

    There may be occasions where we have no need for the index, which brings us onto the next loop: For Each. Which looks like this:

    Code:
    Code:
    For Each <element> As <type> In <collection>

        <instructions>

    Next

    Not unlike the For loop. Here's what's new:

    • <element>

      • Variable scoped to the loop block used to iterate through our collection


    • <collection>

      • A previously-defined collection which we'll iterate through





    Textbook description, let's put it into place with our age array:

    Code:
    Code:
    Dim ages As Integer() = {16, 24, 12, 45, 8}



    For Each age As Integer In ages

        Console.WriteLine("Current age: " & age)

    Next

    Since VB is so pseudo - plain English - it's much easier to see what's going on when applied i.e readable. We can see the instructions will be repeatead for each age in our ages array. Each time, age is changing to the next position at ages. Try it out, you'll get exactly the same result as with standard For.

    Time to combine it with what we've learned so far. Create an array of type Integer and initialize it with the following values: 13, 19, 16, 15, 23. Name it 'ages'. Iterate through this collection and decide if the person is old enough to buy alcohol legally. Decide using a constant of type Integer named 'threshold'. If they are old enough, write the age followed by "is old enough to buy alcohol".

    If not, then declare a new Integer named 'remaining' and calculate how many years until they are old enough using the current age and the threshold as operands. Write the age followed by: "cannot purchase alcohol yet. They may do so in X years" - replacing X with your calculation. There is a solution provided but for your own learning sake, don't open it unless you simply can't complete the assignment.

    Solution (Click to View)

    Take a look at all those lines! You've learned all that, great job so far. There are 2 little extra bits shared in the For family. They are Step and Continue/Exit.

    Step is an optional argument in the For loop. It looks like this:
    Code:
    Code:
    For i As Integer = 5 To 0 Step -1



    Next

    By specifying Step, we can take control of the value our counter is incremented - or decremented - by on each iteration. You'll have noticed by default it's 1. In the above example, we're going backwards from 5 to 0, try it out by printing i if you wish.

    We also have Continue For and Exit For which act as directors. For example:
    Code:
    Code:
    For Each age As Integer In ages

        If age < 5 Then Exit For

    Next

    It'll exit the loop block and move to the next line. We can also use Continue For to ignore the rest of the instructions in the loop block and proceed to the next iteration. This takes us on to the Do group.

    The first is Do While, which looks like this:

    Code:
    Code:
    Do <While|Until> <condition>

        <instructions>

    Loop

    Breaking it down:

    • Do

      • Declares we wish to start a Do loop


    • While

      • Repeat until our condition evaluates as False (booleans!)


    • Until

      • Repeat until our condition evaluates as True


    • <condition>

      • A boolean expression to check against each iteration


    • Loop

      • Terminates our Do block





    Unlike For, these have no definite number of iterations as they loop until a condition is satisfied-- or while a condition is not satisfied. The condition block can be placed at the top or the bottom. Example inverted:
    Code:
    Code:
    Do

        <instructions>

    Loop <While|Until> <condition>

    So what's the difference? If the condition is placed at the top, it will be evaluated and then the loop's instructions executed, so if the condition isn't satisfied, the loop may not run at all. Else if placed at the end, you can guarantee it will run at least once.

    Let's see it in action, keeping with our Integer i:
    Code:
    Code:
    Dim i As Integer = 0



    Do Until i > 5

        Console.WriteLine("Value at i: " & i)

        i += 1

    Loop

    Which we can see prints (Click to View)

    This of course can be inverted to the While counterpart:
    Code:
    Code:
    Dim i As Integer = 0



    Do While i < 5

        Console.WriteLine("Value at i: " & i)

        i += 1

    Loop

    Try running this one.
    Notice anything? (Click to View)

    Correct, it's running only to 4. Why? "Do while Integer 'i', is less then 5." Until 5 is reached, it will continue running. We can repair this by switching our less-than angle bracket with >= - less than or equal to. One last thing: similar to For, we also have Continue/Exit Do. Same reasons!




    That concludes our tutorial on the basics. I hope you've enjoyed reading and if you have feedback, please post it and I'm happy to make adjustments to the thread.

    You're probably thinking to yourself: "Where next?". Well, the next stage is to apply what I've taught you, start by checking out the assignments in the thread. Then, start to set yourself objectives slightly higher than your ability. Research what you don't know BUT importantly, don't blindly copy and paste. Take the time to understand what you've found and it'll come second nature.

    Which brings me on to my next point, programming is no quick skill to pick up. It's mentally demanding and time consuming, requires a lot of patience but the feeling after overcoming some sort of obstacle is immense. Most importantly: enjoy it! It's a fun pastime and can be turned into a (potentially profitable) career.

    For learning materials, there's no better place than Microsoft's own documentation on the Microsoft Developer Network (MSDN): https://msdn.microsoft.com/en-us/library/2x7h1hfk.aspx

    You can search any class, type, engine, library, property, object, whatever available in the .NET framework and Microsoft will have very likely covered it. Another excellent resource is Stack Overflow; not for asking questions, but for answers. As a beginner - and even advanced - chances of you being the first one to run into your problem are very slim. Research exactly what's going wrong but omit the details of your application specifically and you'll likely find an answer here. Same applies with similar sites such as VBForums.

    Best of luck!

  • Admin
    Admin

    Posts : 23
    Join date : 2017-03-11

    View user profile http://toolssupplier.forumieren.de

    Back to top Go down

    View previous topic View next topic Back to top

    - Similar topics

     
    Permissions in this forum:
    You cannot reply to topics in this forum