+ All Categories
Home > Documents > Topik3.4Subprocedures Function

Topik3.4Subprocedures Function

Date post: 04-Apr-2018
Category:
Upload: pabburahati
View: 217 times
Download: 0 times
Share this document with a friend

of 6

Transcript
  • 7/30/2019 Topik3.4Subprocedures Function

    1/6

    3/29/20

    F5227VISUALBASIC.NETPROGRAMMING

    Topic3.0CommonProgrammingTechniques3.4 SubProceduresandFunction

    Procedures

    CourseLearningOutcome(CLO) Upon completion of this course, students should be able to :

    1. Create a simpe VB.NET based application based on the

    Windows Application template.

    2. Describe on essential terminology including memory,

    .

    3. Apply object oriented programming techniques to

    create classes, add methods and add properties.

    4. create a simple VB.NET based Web forms application

    that uses an XML Web Service and manipulate data in

    database by using Microsoft ADO.NET.

    Procedures Procedure aunitofcodethatexecuteswhencalledfrom

    anotherplace.

    NotanewfaceSubproceduredefinition abuttonclickevent

    PrivateSub btnDisplay_Click(ByVal senderAsSystem.Object,

    ByValeAsSystem.EventArgs) HandlesbtnDisplay.Click

    .EndSub

    Or:

    lstOutput.Items.Clear() subprocedurecall

    proceduredefinition Defineswhat toexecutewhentheprocedureiscalled.

    procedurecall Defineswhen toexecutetheprocedure.3

    Procedures Aproceduremusthaveanamefollowingby().

    E.g.

    lstOutput.Items. Clear()

    lstOutput.Items. Add(******)

    CDbl(txtInputOne.Text)

    Purposeofusingprocedures makeyourcodewellorganizedandeasytounderstand.

    4

    ProceduresWithout Using Procedures:Button click event:

    Create variablesTake two user inputs, and

    store them to variablesPerform the addition and

    display the result

    Perform the subtraction andi l l

    Using Procedures:Create variablesButton click event:

    Take two user inputs, andstore them to variables

    Add()Subtract()

    Multiply()i iisplay e resulPerform the multiplication

    and display the resultPerform the division and

    display the result (handle

    divide by 0 situation here)End of event

    ivi eEnd of eventDefine Add():

    Perform the addition anddisplay the result

    Define Subtract():Perform the subtraction and

    display the resultDefine Divide()

    Perform the division anddisplay the result(handledivide by 0 situation here)

    Cont.

    TherearetwotypesofproceduresinVisualBasic.NET:

    9Subprocedures

    Funct onsproce ures

  • 7/30/2019 Topik3.4Subprocedures Function

    2/6

    3/29/20

    Subprocedure

    ASubprocedureisablockofcodethatis

    executedin

    response

    to

    an

    event

    that

    you

    can

    callwithparameterswhichdoesntreturna

    .

    BybreakingthecodeinamoduleintoSubprocedures,itbecomesmucheasiertofindor

    modifythecodeinyourapplication.

    Cont.

    Subproceduresare methods whichdonotreturnavalue.

    EachtimewhentheSubprocedureiscalledthestatementswithinitareexecuteduntilthe

    matchingEndSubisencountered.

    SubMain(), thestartingpointoftheprogramitselfisasubprocedure.

    SubProcedures Sub procedure executeablockofcodeswhencalled

    DefineaSubprocedure:

    Private Sub name()

    actionshere

    ThekeywordPrivate meansthisSubcanonlybeusedbythisForm.

    TheSubprocedurecallmustmatchwiththeSubproceduredefinition.

    9

    SubProcedures E.g.auserdefinedSubdefinitionandSubcall

    PrivateSubbtnCompute_Click(ByVal senderAsSystem.Object,ByVal eAs

    System.EventArgs) HandlesbtnDisplay.Click

    intFirst =CInt(nudFirst.Value)

    intSecond =CInt(nudSecond.Value)

    Add()Subcall.TheprogramwilllookforaSubdefinitionwiththesamenameto ec ew atto o

    EndSub

    SubdefinitionPrivateSubAdd()

    DimintResult AsInteger=0

    intFirstand intSecondareglobalvariables,sotheycanusedbybothSubs.intResult=intFirst +intSecond

    txtAddResult.Text =CStr(intResult)

    EndSub

    10

    SubMain(bytradition)isasubprocedurethatisthefirstsubtobeexecuted,itiswherethe

    programstarts.

    Whenthe

    application

    starts

    execution, control

    istransferredtoMainSubprocedure

    automaticallywhichiscalledbydefault.

    SubProcedures

    Subprocedurescanhavedifferentformalparameters,andtheseformalparameterscan

    beseparatedwithlinecontinuationsfora

    more

    readable

    source

    text. Itcantakearguments,suchasconstants,

    variables,orexpressions,thatarepassedtoit

    bythecallingcode.

  • 7/30/2019 Topik3.4Subprocedures Function

    3/6

    3/29/20

    Syntax

    [Private|Public][Static]Sub

    procedurename (arguments)statementsEndSub

    Example:

    PrivateSubMain()

    Console.WriteLine("Hello there!")

    Console.WriteLine("PressEntertocontinue...")

    Console.ReadLine()

    EndSub

    CallingaSubProcedure

    Onceyouhaveaprocedure,whetheryou

    createdit

    or

    it

    is

    part

    of

    VBasic,

    you

    can

    use

    it.

    Usingaprocedureisalsoreferredtoascalling

    .

    Beforecallingaprocedure,youshouldfirstlocatethesectionofcodeinwhichyouwant

    touseit.

    Tocallasimpleprocedure,typeitsnamefollowedbyparenthesesinthesectionwhere

    youwanttouse.

    ExampleCodeProgram1

    ModuleModule1

    SubMain()

    System.Console.WriteLine("HellofromVisualBasic")

    EndModule

    CodeProgram2

    ModuleModule1

    SubMain()

    DisplayMessage()

    n u

    SubDisplayMessage()

    System.Console.WriteLine("HellofromVisual

    Basic")

    EndSub

    EndModule

    FunctionProcedures

    Functionisamethodwhichreturnsavalue.

    Functionsareusedtoevaluatedata,makecalculationsortotransformdata.

    Declarin

    aFunction

    is

    similar

    to

    declarin

    a

    Subprocedure.

    FunctionsaredeclaredwiththeFunctionkeyword

  • 7/30/2019 Topik3.4Subprocedures Function

    4/6

    3/29/20

    Example

    ModuleModule1

    SubMain()

    EndSub

    ,

    Integer)AsLong

    Returnint1+int2

    EndFunction

    EndModule

    Explaination

    Returnavaluefromafunctionwiththe

    Return statement Theprogramreturningthesumofthetwo

    .

    Whencallafunctionbyusingitsnameandan

    argumentlistenclosedinparentheses,that

    nameisreplacedbythevaluereturnedbythe

    function

    Example

    ModuleModule1

    SubMain()

    DimintValueAsInteger=2

    System.Console.WriteLine("{0}+{1}={2}",_intValue,

    nt a ue, em nt a ue, nt a ue

    EndSub

    FunctionAddem(ByValint1AsInteger,ByValint2AsInteger)

    AsLong

    Returnint1+int2

    EndFunction

    EndModule

    PassingParameters

    Parameterscanbepassedtoaprocedureinoneoftwoways.

    Eitherbyreference(ByRef)orbyvalue(ByVal).

    When ouusetheb re erence methodchangesmadetoparameters'valuesinasub

    procedureareknownwhencontrolreturns

    backtothecallingprocedure

    ByRefisthedefaultmethodofparameterpassinginVB6andpriorversionswhenthe

    parameter'sdatatypeisanintrinsiconesuch

    as

    Integer,

    Long,

    Boolean,

    String,

    etc

    ByVal

    Thensecondmethodispassbyvalue(ByVal).

    Thisisthedefaultforallnonintrinsicdatatypes.

    W enpasse yva ue,t eca ngproce ureknowsnothingaboutchangesmadetothe

    parameter'svalueinasubprocedure.

  • 7/30/2019 Topik3.4Subprocedures Function

    5/6

    3/29/20

    VB.NETpassesallparametersByVal.

    Thus,don'trelyonthedefaultbehaviorand

    alwaysexplicitly

    specify

    ByVal or

    ByRef in

    your

    parameterlists.

    AModuleforVB.NETisafile(endingin.vb)thatcontainsprogramcodeandsub

    proceduresto

    execute.

    Youmayalsoincludemodulesintoother

    projectstocallon.

    Accessibility

    TheaccessibilitycanbePublic,Protected,Friend,ProtectedFriend,orPrivate.

    YoucandefineSub proceduresinmodules,, .

    TheyarePublic bydefault,whichmeansyou

    cancallthemfromanywhereinyour

    application.

    Syntax

    [accessibility]Subsubname[(argumentlist)]

    'StatementsoftheSubproceduregohere.

    EndSub

    Example:

    PrivateSubDisplayMessage(ByValstrTextAsString)

    ArgumentDeclaration Youdeclareeachargumentforaprocedure

    thesamewayyoudeclareavariable,

    specifyingtheargumentnameanddatatype.

    ,

    andwhethertheargumentisoptional.

    ArgumentSyntax

    [Optional][ByVal|ByRef] [ParamArray] argumentnameAsdatatype

    Iftheargumentisoptional,youmustalsosupplyadefaultvalueinits

    declaration,asfollows:

    CopyOptional[ByVal|ByRef] argumentnameAsdatatype=defaultvalue

  • 7/30/2019 Topik3.4Subprocedures Function

    6/6

    3/29/20

    LocalVariablesandGlobalVariables

    LocalVariables:

    Purpose: foraspecificproceduretouse

    Scope:onlyusedinsidethatprocedure

    Where:createdinsideaprocedure

    31

    GlobalVariables:

    Purpose:avariablesharedbydifferentprocedures

    Scope:theform,alsocalledformvariables,canbeusedanywhereinthesameform

    Where:createdatthebeginningoftheClass,outsideofanyprocedures

    LocalVariablesandGlobalVariables

    Local Variables:Add Button click event procedure:

    3 local variables, only used

    inside this procedure

    Create variables 1, 2, and 3Take user input and store invariable 1 and 2

    Add variable 1 to variable 2l

    Global Variables:Create 2 global variables outside of

    any procedure, can be used anywhere

    Create variables 1, 2Add Button click event procedure:

    Add()End of event procedureProcedure Add():

    1local variable onl usedlvariable 3

    End of event procedure

    ,

    inside this procedure

    Create variable 3use global variable 1 and 2

    Take the user input and storein variable 1 and 2

    use global variable 1 and 2, andlocal variable 3

    Add variable 1 to variable 2and store the result tovariable 3

    End of Add procedure

    Conclusion

    ASub procedureisaseriesofVisualBasic

    statementsenclosedbytheSub andEndSubstatements.

    Eachtimetheprocedureiscalled,its

    statementsareexecuted,startingwiththefirst

    executablestatementaftertheSub statement

    andendingwiththefirstEndSub,ExitSub,orReturnstatementencountered.


Recommended