.Net Programming - Financial independence

How to Work with Functions and Subs in Visual Basic

This is also an important topic, the functions. But wait, Visual Basic is special in a way that it has two types of functions, Subs and Functions, we will see the what makes both types different.

What is a function?

Let’s start by defining what is a Function. A function is a piece of code that acts like a block, you can then access this block from somewhere else in your program. It’s a way of dividing your program into logical functionalities.

Note: There is no real way to know how many functions you should have in you software, too many functions is not better than one big 1000 lines straight piece of code. One advice I can give you (based on my own experience) is, look for pieces of code that you copy pasted, or acts somewhat the same way. You can then try to build a Function around it and save a couple of lines, keep everything nice and clean!

Start a new project and follow my instructions! How do we create a function?

Module Program
    Sub Main()

    End Sub

    Private Function ExecuteSomeTask() As Integer
        Return 6
    End Function
End Module

As you can see, we still have our Main(), but I added something new inside the Module Program (a module can contain Functions and Subs). We can divide the Function code into a few parts.

Private: defines the function scope (from where can this Function be accessed in your code. Right now the function can only be accessed by what is inside of the Program Module, in this case, Main()).
Function: is the keyword for defining a Function or if you prefer, telling Visual Basic that this block will be a Function.
ExecuteSomeTask: is the name of the Function, it can be anything, but try to name it according to what it will be doing. It should be an action, for example: CountToOneHundred().
(): The parenthesis will be used later, but they are here for parameters we will pass to the function so it can work with them and produce and output.
As Integer: will be the return type, remember that what is special about a function is that it has a return value or, if you prefer, an output, something that will come out of it. In our case it’s going to be an Integer value. We always know the type that will be returned.
End Function: simply defines the end of the function block.

That’s pretty nice you say, but how do we use such a thing in the real world?

Lets pretend we want to create a code that is going to count the number of letters in a word we specify. We will use a function because this functionality might be used somewhere else in our code and we don’t want to copy and paste code every time.

The function will have the purpose of counting the number of letters in the word and return this number. Here is the solution.

Module Program
    Sub Main()
        Dim InputWord As String
        Dim NumberOfLetters As Integer
        Dim ResultSentence As String

        InputWord = "MyWord"
        NumberOfLetters = 0
        ResultSentence = ""

        NumberOfLetters = CountNumberOfLettersInWord(InputWord)
        ResultSentence = String.Format("{0} contains {1} letters", InputWord, NumberOfLetters)

    End Sub

    Private Function CountNumberOfLettersInWord(ByVal WordToAnalyse As String) As Integer
        Dim NumberOfLetters As Integer

        NumberOfLetters = 0

        For Each Letter As Char In WordToAnalyze
            NumberOfLetters += 1

        'Return the value
        Return NumberOfLetters
    End Function
End Module

Step Into!

Wow this code is huge! We will need to take it slow! I want you to first put a breakpoint at the Dim InputWord As String and follow the computer using F10 or Step over like in tutorial 7. What happened when the highlighted line was on CountNumberOfLettersInWord function and you clicked F10? It went straight to the next line. Let’s say we want it to go into the Function itself to see what is going on in there. Once you are on the function line, click on F11 or Step Into. This makes the computer dive into the function.

Questions and code review

Perfect, but we still got a large amount of unknown code in there. What is going on at the line: NumberOfLetters = CountNumberOfLettersInWord(“MyWord”).
It looks a bit like what we did with Console.WriteLine(“Text to write”), we pass the text to write to the function WriteLine so it can write something into the console. It’s the same idea here. “MyWord” is of type String, and will be passed to CountNumberOfLettersInWord which accepts only type String as parameters -> ByVal WordToAnalyze As String.

I don’t understand what is WordToAnalyze then? It’s a variable that will contain what you passed to the function. In this case, “MyWord” will be assigned to WordToAnalyze. The Function can then use this variable to do its processing. Keep in mind that WordToAnalyze will only be visible in the Function block, no one else can use this variable!

What is For Each…? That’s a loop, we will see them in the next tutorial! Don’t worry about this for now. It counts the number of letters in WordToAnalyze.

I don’t understand what this line is doing? NumberOfLetters = CountNumberOfLettersInWord(“MyWord”), this line takes what is returned by CountNumberOfLettersInWord and puts the result in the Integer Variable NumberOfLetters. Visual Basic knows that this operation is correct because CountNumberOfLettersInWord returns a Integer type.

What is ByVal? ByVal is a special keyword that tells Visual Basic to create a new variable that won’t affect what is outside of the function itself. For example, if you pass a variable to a Function and modifications are made to this variable inside the Function, it won’t be affected outside of the Function itself. Its counterpart is ByRef which makes changes to a variable inside a function affecting the variable outside as well! Careful with that, ByVal is generally safer to use!

What you have to remember about functions

Function parts

A Function needs a return value! (Blue rectangle)
A Function can take 0, 1 or multiple parameters like WordToAnalyze, if you have many, they will be separated by commas. (Red rectangle)
A Function is used to divide the code into smaller, logical parts. It can also be used to counter repetition of code that will be hard to maintain later.
A Function can have a scope, like a variable, this means it can or cannot be accessed from certain parts of your code. If it’s private it’s going to be accessible inside the owner only, in that case, inside the Module Program. (Green rectangle)
A Function has a name that you can define, however, I strongly suggest a name that states what the Function does in a straightforward way. For example, AddItem, WriteToConsole, RemoveCharacter, etc. (Purple rectangle)

Please refer to the image for the colors.

Need more information? You can go directly to the MSDN Website.

So… what is a Sub then?

Basically, a Sub is a function that has no return value! That’s it! Visual Basic simply uses another name to define them. Again I have a nice link on Subs from Microsoft just for you! If you wish to know more about the Subs.

There will be an exercise (3) on the subject as this can be tricky to understand.

Next article How Loops Work in Visual Basic
Previous article How to Add Line Numbers in Visual Studio

Related posts


No Comments Yet!

You can be first to comment this post!

Leave a Comment

Your data will be safe! Your e-mail address will not be published. Also other data will not be shared with third person. Required fields marked as *