Subroutines & FunctionsSubroutineA subroutine is a code construct.
A code construct is a pattern of coding. Examples;- For Loops, Do Whiles Loops, Sub ... End Sub, Function .... End Function
A subroutine is a self contained section of code, that;-
Has Inputs: Possible
Has Output: Never
CODE
Private Sub PrintHelloWorld()
Console.WriteLine("Hello World")
End Sub
Where you put your code to handle a button click is particular type of subroutine called
An Event HandlerIndicated by the
Handles Button1.Click.
CODE
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
FunctionsA function is a self contained section of code, that;-
Has Inputs: Generally Yes
Has Output: Always
CODE
Function SquareOfNumber(ByVal x As Decimal) As Decimal
Return x * x
End Function
Subroutines & Functions may contain calls to other Functions and Subroutines.
CODE
Function Factorial(ByVal x As Decimal) As Decimal
Dim f As Decimal = 1
While x > 1
f = f * x
x -= 1
End While
Return f
End Function
Function FactorialSquared(ByVal x Decimal) As Decimal
Return SquareOfNumber(Factorial(x))
End Function
Thats the basics of Functions & Subroutines.
For the more the adventurousQ. What all the arguments of the preceding Functions & Subroutines have in common?
A. All the arguments are preceded by a
ByVal.
There are to basic types (the object type of the arguments excluded) of argument.
ByVal This a
copy of the object passed in. You can do what you like to this and it won't change the original object passed in as the argument.
ByRef This a
REFerence to the actual object. What you do to this affects the original object passed in as the argument.
A
ByRef argument allows the programmer to get information out of a Subroutine, like a Function.
Example 1 (Trivial): Increase the value of two Doubles by 2.
CODE
Public Sub IncreaseBothBy2(ByRef A As Double,ByRef B As Double)
A+=2
B+=2
End Sub
Example 2: Clear the text of any textbox.
CODE
Sub ClearTextbox(ByRef Tb As Textbox)
Tb.Text=""
End Sub
I hope now you'll be a Function & Subroutine wielding Code-Ninja.
Edit: Mismatched tag
Edit: The 100th VB.net Tutorial on DiC
This post has been edited by AdamSpeight2008: 7 Apr, 2009 - 06:04 AM