VB.NET Sub

Array Class Collections File String Cast Console Data Directive Enum Exception If Interface Lambda LINQ Loop Nothing Number Process Property Regex Select Sort StringBuilder Structure Sub Time Windows

Sub

Subs, functions. In VB.NET,
Subs
and Functions contain behavior. A Sub procedure returns no value. Functions return a value, often based on a variable.


ByVal and ByRef operators

Parameters. Procedures optionally have argument lists and formal parameters. A parameter influence a procedure's behavior. Parameters can be passed ByVal or ByRef.

ByVal, ByRef

ByVal:The parameter's location is local. When chanced in a procedure body, no other values are affected.

ByRef:The parameter's location is shared with the calling location. A change is reflected outside the procedure.


The VB.NET programming language

Example sub. We declare and call a Sub procedure. We use different syntaxes to call the procedure. The program also shows XML comments. Subroutines return no value to the caller.

Result:This program uses Console.WriteLine and prints ten numbers to the console screen.

Tip:Please notice how the underscore character is used. It allows a line break to occur in a Sub call.

Based on:

.NET 4.0

Program that uses Sub procedure: VB.NET

Module Module1

    Sub Main()
	'
	' Call the Sub Procedure, which returns no value.
	' ... You can put all the arguments on one line.
	'
	WriteArguments(1, 2, 3, 4, 5)
	'
	' Call the Sub Procedure again.
	' ... You can use the line continuation marker to break up the lines.
	'
	WriteArguments(1000, _
	    2000, _
	    3000, _
	    4000, _
	    5000)
    End Sub

    ''' <summary>
    ''' Prints out the five arguments.
    ''' </summary>
    ''' <param name="param1">Description 1.</param>
    ''' <param name="param2">Description 2.</param>
    ''' <param name="param3">Description 3.</param>
    ''' <param name="param4">Description 4.</param>
    ''' <param name="param5">Description 5.</param>
    ''' <remarks>Made by Dot Net Perls.</remarks>
    Sub WriteArguments(ByVal param1 As Integer, _
		       ByVal param2 As Integer, _
		       ByVal param3 As Integer, _
		       ByVal param4 As Integer, _
		       ByVal param5 As Integer)
	Console.WriteLine(param1)
	Console.WriteLine(param2)
	Console.WriteLine(param3)
	Console.WriteLine(param4)
	Console.WriteLine(param5)
    End Sub

End Module

Output

1
2
3
4
5
1000
2000
3000
4000
5000

Print

Some notes. Above we see a method called WriteArguments. The Main Sub first calls the WriteArguments subroutine with a single line of arguments.

Note:The WriteArguments sub prints 5 integers on separate lines. Console.WriteLine, too, is a Sub.

Underscore:Next, we can separate a long line when calling or declaring a function. We use an underscore as a line continuation.


Extensible markup language: XML

XML comments. To add an XML-based comment to a function, type three single-quote characters. Then insert the text inside the XML tags that appear.

Info:XML comments are used in Visual Studio's interface. They make large programs easier to develop.


Return keyword

Functions. Let us contrast the Function type to the Subtype. The Sub does not return a value to its caller. But a Function returns a value.

Function
Program that uses Function: VB.NET

Module Module1

    Function MultiplyByTwo(ByVal test As Integer) As Integer
	Return test * 2
    End Function

    Sub Main()
	' Call the Function with an argument of 5.
	Console.WriteLine(MultiplyByTwo(5))
    End Sub

End Module

Output

10

As-cast

As-keyword. In VB.NET, the As-keyword is used to indicate a type. In a parameter, As describes the type of the parameter. And in a Function, As describes the return value's type.


About part

Shared. A Function or Sub can be shared throughout all instances of the enclosing class. An instance reference is not needed to call a Shared Function.

Shared
Program that calls Shared Sub: VB.NET

Class Utility
    ''' <summary>
    ''' Displays a helpful message.
    ''' </summary>
    Public Shared Sub Message()
	Console.WriteLine("Hello world")
    End Sub
End Class

Module Module1
    Sub Main()
	' We do not use a Utility instance to call the shared Sub.
	Utility.Message()
    End Sub
End Module

Output

Hello world

Tip

A comment is best written at the level of intention. We explain what the code is meant to accomplish. Comments that simply translate the code to English are less effective.

But:Comments sometimes help emphasize certain aspects of programs. If a computation is important, a comment makes it more prominent.

Program that uses comments: VB.NET

Module Module1
    REM This is Module1.

    ''' <summary>
    ''' This is an XML comment.
    ''' </summary>
    ''' <remarks>Called at program start.</remarks>
    Sub Main()
	REM Get square root of 225.
	Dim value As Double = Math.Sqrt(225)

	' Print value. (Other comment syntax.)
	' ... Sometimes it helps to indent comments.
	Console.WriteLine(value)
    End Sub
End Module

Output

15

Program

Comment syntax. We use three comment syntax forms. REM stands for an explanatory remark. All characters following REM are not code statements.

And:When three apostrophes are at the start of the comment, this is an XML comment.

XML comments:These are used by Visual Studio to help programmers navigate and discover your code. Certain XML tags can be added.

Apostrophe:The simplest comment form starts with a single apostrophe. This is probably the easiest syntax for comments.


Syntax

Underscore. This language does not allow line breaks everywhere. A newline signals the end of a statement. But an underscore allows a statement to span many lines.

First:The first program uses a statement on a single line. This statement uses generic types.

Second:The second program uses the underscore syntax at the end of lines. This means the statement can continue on the next line.

Program with long statement: VB.NET

Module Module1
    Sub Main()
	Dim longerVariableName As Dictionary(Of String, KeyValuePair(Of Boolean, ....
	longerVariableName("a") = Nothing
    End Sub
End Module

Program with statement on multiple lines: VB.NET

Module Module1
    Sub Main()
	Dim longerVariableName _
	    As Dictionary(Of String, KeyValuePair(Of Boolean, Integer)) = _
	    New Dictionary(Of String, KeyValuePair(Of Boolean, Integer))(5000)
	longerVariableName("a") = Nothing
    End Sub
End Module

Operator keyword

AddressOf. This operator allows us to reference a Function or Sub by its name. We can then pass the result to another Function. Here, Array.FindIndex requires a Predicate argument.

AddressOf

Note:The AddressOf IsMatch syntax returns a suitable function as a Predicate instance.

Note 2:With AddressOf we can change a Function or Sub name into an argument, a variable, that we can pass to other procedures.

Program that uses AddressOf: VB.NET

Module Module1

    Function IsMatch(ByVal item As String) As Boolean
	Return item.Length = 4
    End Function

    Sub Main()
	Dim items() As String = {"cat", "apple", "baby"}
	' Use AddressOf to specify IsMatch as the Predicate.
	Dim index As Integer = Array.FindIndex(items, AddressOf IsMatch)
	Console.WriteLine(index)
    End Sub

End Module

Output

2

Method

Extension. An extension method is not an instance method. But it is called with the same syntax as one. We apply the <Extension()> syntax.

Extension Method
Squares: grey

Lambda expressions. We can use the Sub and Function keywords to declare lambda expressions directly in other method bodies. Lambdas act like any other method.

Lambdas
Squares: grey

Recursion. When a Function calls itself, recursion occurs. The ByRef keyword can be useful when implementing recursive algorithms.

Recursion
About part

With. The VB.NET language has some syntactic sugar. One example is the With statement. This reduces the typing necessary in some contexts.

With
Const keyword

Const. A Const value is used with syntax similar to a field or local variable. But it cannot be reassigned. It can only be initialized.

Const
Structure

Structures. When a method is called, a structure argument is copied fully to the method's local memory. A Class argument is not—only its reference is copied.

Structure, Arguments
Maze: many paths are possible, confusion abounds

In algorithms, we combine data structures and functions to achieve complex tasks. An algorithm is a well-known (or complex) method.

Fibonacci:We compute the Fibonacci sequence in VB.NET with a simple For-loop. Each number is the sum of the previous two.

Fibonacci Sequence

Levenshtein:With this algorithm, we compute the "edit distance" between two strings. This tells us string similarity.

Levenshtein

Procedures are everywhere. The Sub procedure syntax is often used in VB.NET programs. Subroutines (Subs) return no value. We compared Subs with Functions.

VB.NET