Nesting Revisited


Earlier in the chapter, we covered the concept of nesting. In that section, you had only seen loops before, so our discussion of nesting was limited. Now, though, you have also seen the concepts of functions and procedures, so let's look at how you can apply nesting to these kinds of code blocks. Some of these examples aren't strictly speaking nesting, but more like combining of different structures. The important thing to understand in each case is how each of these structures can be combined.

There are lots of ways to use nesting in Visual Basic .NET, so here is a quick reference:

  • You can put decisions and loops inside procedures and functions:

    Function myFunction() As Integer   Do While condition     ' This will work   Loop   If condition Then     ' So will this   End If End Function
  • You can call procedures and functions from inside loops and decisions:

    Do While condition   x = myFunction() Loop If condition Then   myProcedure() End If
  • You can put loops inside decisions:

    If Not sheLovesMe Then   Dim n   For n = 1 to 100     Label1.Text = Label1.Text & "I love you! <br/>"   Next n End If
  • You can put decisions inside loops:

    Dim n For n = 1 to 100   Label1.Text = Label1.Text & "I love you! <br/>"   If sheLovesMe Then     Exit For   End If Next n 
  • You can have a loop within a loop, or a decision within a decision:

    If testScore >= 50 Then   Label1.Text = "Well done you passed"   If testScore >= 80 Then     Label1.Text = "... with a distinction – well done!"   End If End If
  • But you cannot put one method definition (that is, a function or procedure) inside another:

    Function myFunc() As Integer   Sub myProcedure()     ' THIS WON'T WORK   End Sub End Function

    Although you can't create one method within another, you can call a function or procedure from within another function or procedure, so the following would be acceptable:

    Function myFunc() As Integer   myProcedure() End Function

    We saw this in action briefly when we looked at the age example during our discussion of procedures.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net