|
|
|
|
|
|
|
|
|
|
|
|
|
Public Class Hello
Shared Sub Main()
System.Console.WriteLine("Hello World...")
End Sub
End Class
>vbc foo.vb /target:exe
>foo
Error! Sub Main was not found in foo.Module1
Reason: no top class known. In Solution Explorer window set foo --> Properties --> Common Properties --> General --> Startup object to Hello or Sub Main).
>foo
Public Class Hello
Shared Sub Main()
System.Console.WriteLine("Hello World...")
System.Console.WriteLine()
do_this()
System.Console.WriteLine()
End Sub
Shared Sub do_this()
Dim first As Int16 = 32767
Dim second As Int16 = 0
Dim result As Int16
result = first + second
System.Console.WriteLine(CStr(result))
End Sub
End Class
Sub my_sub()
some code
some more code
End Sub
Function my_function()
some code
some more code
return some_value
End Function
Public Class Hello
Shared Sub Main()
dim my_var as int16
System.Console.WriteLine("Hello World...")
System.Console.WriteLine()
my_var = do_this()
System.Console.WriteLine(CStr(my_var))
End Sub
Shared Function do_this() as int16
Dim first As Int16 = -99
Return first
End Function
End Class
This begs the question of why to use subroutines at all??
Answer: BASIC has always been a 'permissive' language; i.e., lenient on type
checking. The new .NET approach requires strict type checking (as do C/C++/Java).
To enforce this:
Option Strict On (on by default in VS.NET 2003)
Option Explicit On
Public Class Hello
Shared Sub Main()
Dim my_var As Short = 10
System.Console.WriteLine("Hello World...")
System.Console.WriteLine()
do_this(my_var)
System.Console.WriteLine(CStr(my_var))
End Sub
Shared Sub do_this(ByVal foo As Short)
foo = foo * CShort(10)
End Sub
End Class
- Notice how strict type checking forces you to convert '10' into a short using Cshort(10).
- foo is not multiplied by 10 when printed out in Main(). Cause: When passing a variable by value (ByVal), only the value of the variable is passed, not the variable itself (a memory copy local to the function/subroutine is created) (default in C).
- To access the passed variable itself, pass by reference (ByRef) (pointer/address in C).
- Notice that regardless how passed (ByVal or ByRef), the variable names in the caller and the function/subroutine can be different. ByRef implies that memory is not copied (only the address (pointer) is passed); the name of the local reference to that memory is immaterial.