Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Visual Basic Language » Control Statements in VB.NET: Part 2

Control Statements in VB.NET: Part 2

In this article I will explain your about different control statements in VB.NET.

Author Rank :
Page Views : 1347
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


HTML clipboard

As you learn some control statement in previous article here is part 2 of remaining controls statement.

Control statements give you additional means to control the processing within the applications you develop. This section explores the syntax and function of the do-while, foreach, goto, exit, continue, and return statements.

While

The while loop allows the user to repeat a section of code until a guard condition is met. Listing 5.27 presents a simple while loop designed to find out the number of digits in a given value.

Listing 5.27: While Example

        'find out the number of digits in a given number
        Dim i As Integer = 123
        Dim count As Integer = 0
        Dim n As Integer = i
        
'while loop may execute zero times
        While i > 0
            System.Threading.Interlocked.Increment(count)
            i = i / 10
        End While
        Console.WriteLine("Number {0} contains {1} digits.", n, count)

For a given number i = 123, the loop will execute three times. Hence the value of the count is three at the end of the while loop.

This example has one logical flaw. If the value of i is 0, the output of the code will be "Number 0 contains 0 digits." Actually, the number 0 contains one digit. Because the condition of the while loop i > 0 is false from the beginning for the value i = 0, the while loop does not even execute one time and the count will be zero. Listing 5.28 presents a solution.

Listing 5.28: Do Example

        'find out the number of digits in a given number
        Dim i As Integer = 0
        Dim count As Integer = 0
        Dim n As Integer = i
        Do
            System.Threading.Interlocked.Increment(count)
            i = i / 10
        Loop While i > 0
        Console.WriteLine("Number {0} contains {1} digits.", n, count)

The do-while construct checks the condition at the end of the loop. Therefore, the do-while loop executes at least once even though the condition to be checked is false from the beginning.

ForEach

The For Each statement allows the iteration of processing over the elements in arrays and collections. Listing 5.31 contains a simple example.

Listing 5.31: For Each Example 1

        'foreach loop
        Dim a As String() = {"Chirag", "Bhargav", "Tejas"}
        For Each b As String In a
            Console.WriteLine(b)

        Next

Listing 5.32 presents a slightly more complex version of the foreach loop.

Listing 5.32: ForEach Example 2

        Dim intNumbers As Int16() = {4, 5, 6, 1, 2, 3, -2, -1, 0}
        For Each i As Int16 In intNumbers
            System.Console.WriteLine(i)
       
Next

Each iteration queries the collection for a new value for i. As long as the collection intNumbers returns a value, the value is put into the variable i and the loop will continue. When the collection is fully traversed, the loop will terminate.

GoTo

You can use the goto statement to jump to a specific segment of code, as shown in Listing 5.33. You can also use goto for jumping to switch cases and default labels inside switch blocks. You should avoid the overuse of goto because code becomes difficult to read and maintain if you have many goto jumps within your code.

Listing 5.33: GoTo Example

        label1:

         '...
        If x = 0 Then
            GoTo label1
        End
If
Exit

The exit statement, used within for, while, and do-while blocks, causes processing to exit the innermost loop immediately. When a break statement is used, the code jumps to the next line following the loop block, as you'll see in Listing 5.34.

Listing 5.34: Exit Example

While True
            '...
            If x = 0 Then
                Exit While
                '...
            End If
        End While
        Console.WriteLine("Exit")
   
Continue

The continue statement (shown in Listing 5.35) is used to jump to the end of the loop immediately and process the next iteration of the loop.

Listing 5.35: Continue Example

While True
            '...
            If x = 0 Then
                x = 5
                Continue While
            End If
            '...
             If x = 5 Then
                Console.WriteLine("continue")
                '...
            End If
        End
While

Return

The return statement is used to prematurely return from a method. The return statement can return empty or with a value on the stack, depending upon the return value definition in the method (Listing 5.36 shows both). Void methods do not require a return value. For other functions, you need to return an appropriate value of the type you declared in the method signature.

Listing 5.36: Return Example

Sub MyFunc1()
        ' ...
        If x = 1 Then
            Return
        End If
        ' ...
End Sub
     Function MyFunc2() As Integer
        ' ...
        If x = 2 Then
            Return 1919
        End If
        ' ...
    End
Function

Conclusion

Hope this article would have helped you in understanding control statements in VB.NET.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Manish Tewatia
Manish is Very much interested in Microsoft & LifeStyle Accessory Designand working with Microsoft technologies. His expert areas are ASP.NET, ADO.NET, C# .NET, WPF, WCF, Windows Phone 7, Android, SQL Server, HTML , XAML, etc…
He is doing MCA and he love to drive fast bikes.
inspired from Mr. Mahesh Chand.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Mindcracker MVP Summit 2012
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.