.NET HELP

C# Continue (How It Works For Developers)

Published April 29, 2024
Share:

Introduction

Control flow statements are crucial in programming, as they dictate the execution sequence of instructions within a program. In C#, three fundamental statements for controlling loops are 'continue', 'break', and 'goto'. These statements provide programmers with the ability to alter the flow of execution within loops, enhancing code efficiency and readability. In this article, we delve into the intricacies of continue and break methods in C#, exploring their syntax, applications, and best practices. Later in the article, we will also learn about IronPDF from Iron Software to read and write PDF documents.

Understanding the 'continue;' Statement

The continue statement is used within loop structures to skip the remaining code block and proceed to the next iteration of the loop. It essentially tells the program control to skip the current iteration's remaining code and move on to the next iteration.

Syntax

continue;
continue;
continue
VB   C#

Example

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Demonstrate Continue Method in C#");
        Console.WriteLine("Print 1 to 10 skip 5");
        for (int i = 0; i < 10; i++)
        {
            if (i == 5)
            {
                continue; // Skips iteration when i equals 5
            }
            Console.WriteLine(i);
        }
    }
}
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Demonstrate Continue Method in C#");
        Console.WriteLine("Print 1 to 10 skip 5");
        for (int i = 0; i < 10; i++)
        {
            if (i == 5)
            {
                continue; // Skips iteration when i equals 5
            }
            Console.WriteLine(i);
        }
    }
}
Public Class Program
	Public Shared Sub Main()
		Console.WriteLine("Demonstrate Continue Method in C#")
		Console.WriteLine("Print 1 to 10 skip 5")
		For i As Integer = 0 To 9
			If i = 5 Then
				Continue For ' Skips iteration when i equals 5
			End If
			Console.WriteLine(i)
		Next i
	End Sub
End Class
VB   C#

In this example, when i equals 5, the continue statement is executed, skipping the remaining code within the loop for that iteration. As a result, the number 5 will not be printed, and the loop goes to the next iteration.

Output

C# Continue (How It Works For Developers): Figure 1 - Console output showing case 5 is skipped due to continue statement

Exploring the 'break;' Method

Contrary to continue, the break statement is used to exit a loop prematurely. When encountered, it terminates the loop's execution, regardless of the loop's condition. It's commonly used to exit a loop such as a while loop, early if a certain condition is met.

Example

int [] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (int number in numbers)
{
    if (number == 6)
    {
        break; // Exits loop when number equals 6
    }
    Console.WriteLine(number);
}
int [] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (int number in numbers)
{
    if (number == 6)
    {
        break; // Exits loop when number equals 6
    }
    Console.WriteLine(number);
}
Dim numbers() As Integer = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
For Each number As Integer In numbers
	If number = 6 Then
		Exit For ' Exits loop when number equals 6
	End If
	Console.WriteLine(number)
Next number
VB   C#

In this example, the loop iterates through the numbers array. When it encounters the number 6, the break statement is executed, causing the loop to terminate prematurely. As a result, only numbers 1 through 5 will be printed.

Explore 'goto;' statement

The goto statement in C# provides a way to transfer control to a specified label within the same method, within the same switch statement, or within the same loop. While goto can be a powerful tool for altering the flow of execution to jump statements, it is often discouraged in modern programming practices due to its potential to make code less readable and maintainable. However, there are situations where goto can be used effectively and safely.

Syntax

The syntax of the goto statement in C# is straightforward:

goto label;
goto label;
GoTo label
VB   C#

Where the label is an identifier followed by a colon (:), indicating the target location in the code.

Example

Consider a scenario where you want to exit a nested loop prematurely when a specific condition is met. You can achieve this using a goto statement:

for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 5; j++)
    {
        if (i * j > 10)
        {
            goto exitLoop;
        }
        Console.WriteLine($"i: {i}, j: {j}");
    }
}
exitLoop:
Console.WriteLine("Exited the nested loop prematurely.");
for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 5; j++)
    {
        if (i * j > 10)
        {
            goto exitLoop;
        }
        Console.WriteLine($"i: {i}, j: {j}");
    }
}
exitLoop:
Console.WriteLine("Exited the nested loop prematurely.");
For i As Integer = 0 To 4
	For j As Integer = 0 To 4
		If i * j > 10 Then
			GoTo exitLoop
		End If
		Console.WriteLine($"i: {i}, j: {j}")
	Next j
Next i
exitLoop:
Console.WriteLine("Exited the nested loop prematurely.")
VB   C#

In this example, the goto statement transfers control to the exitLoop label when the condition i * j > 10 is met, effectively breaking out of the nested loop.

Introducing IronPDF from Iron Software.

IronPDF, developed by Iron Software, is a powerful C# PDF library that provides an all-in-one solution for working with PDFs in .NET projects. Whether you need to create, edit, export, secure, load, or manipulate PDF documents, IronPDF has got you covered. Here are some key features and use cases:

  1. HTML to PDF Conversion: Convert HTML content to PDF format seamlessly. You can generate PDFs from HTML, MVC, ASPX, and even images.
  2. Sign, Edit, and Read PDFs: With over 50 features, IronPDF enables you to sign, edit, and extract content from PDF files. Whether you’re adding digital signatures or modifying existing PDFs, IronPDF makes it straightforward.
  3. Cross-Platform Support: IronPDF is designed for C#, F#, and VB.NET, and it runs on various .NET versions, including .NET Core, .NET Standard, and .NET Framework. It’s also available for Java, Node.js, and Python.
    1. Compatibility and Environments:
      • .NET Versions: Supports C#, VB.NET, and F#.
      • Project Types: Works with web (Blazor & WebForms), desktop (WPF & MAUI), and console applications.
      • App Environments: Compatible with Windows, Linux, Mac, Docker, Azure, AWS, and more.
      • IDEs: Integrates seamlessly with Microsoft Visual Studio and JetBrains Rider.
      • OS & Processors: Runs on Windows, Mac, and Linux (x64, x86, ARM).
    2. PDF Standards and Editing:
      • Supports various PDF versions (1.2 - 1.7), PDF/UA, and PDF/A.
      • Set properties, security, and compression for PDF files.
      • Edit metadata, revision history, and document structure.
      • Apply page templates, headers, footers, and page settings.
    3. Performance Optimization:
      • Full multithreading and async support for efficient PDF generation.
      • Prioritizes accuracy, ease of use, and speed.

Now that we are aware of IronPDF library, let us write an application to use IronPDF and continue statement, break statement, and goto Statement.

Generate PDF Document Using Continue Statement

First, let's create a Visual Studio console application

C# Continue (How It Works For Developers): Figure 2 - Creating a Visual Studio console app

Provide the project name and location.

C# Continue (How It Works For Developers): Figure 3 - Provide the project name

Next Step, select the required .NET version and click Create.

Now install IronPDF using the command below.

dotnet add package IronPdf --version 2024.4.2
dotnet add package IronPdf --version 2024.4.2
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf --version 2024.4.2
VB   C#

Now let us generate a PDF document using the control statements.

using System;
using System.Threading.Tasks;
using System.Diagnostics;
using IronPdf;
class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Generate PDF document Using IronPDF");
        var htmlToPdf = new ChromePdfRenderer();
        var content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>";
        for (int i = 0; i < 10; i++)
        {
            if (i == 5)
            {
                continue;
            }
            content += $"<p>{i}</p>";
        }
        content += "<h1>Generate Numbers from 1 to 10, stop at 7</h1>";
        for (int i = 0; i < 10; i++)
        {
            if (i == 7)
            {
                break;
            }
            content += $"<p>{i}</p>";
        }
        var pdf = htmlToPdf.RenderHtmlAsPdf(content);
        pdf.SaveAs("AwesomeIronPDF.pdf");
        Console.WriteLine("PDF generated successfully.");
    }
}
using System;
using System.Threading.Tasks;
using System.Diagnostics;
using IronPdf;
class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Generate PDF document Using IronPDF");
        var htmlToPdf = new ChromePdfRenderer();
        var content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>";
        for (int i = 0; i < 10; i++)
        {
            if (i == 5)
            {
                continue;
            }
            content += $"<p>{i}</p>";
        }
        content += "<h1>Generate Numbers from 1 to 10, stop at 7</h1>";
        for (int i = 0; i < 10; i++)
        {
            if (i == 7)
            {
                break;
            }
            content += $"<p>{i}</p>";
        }
        var pdf = htmlToPdf.RenderHtmlAsPdf(content);
        pdf.SaveAs("AwesomeIronPDF.pdf");
        Console.WriteLine("PDF generated successfully.");
    }
}
Imports System
Imports System.Threading.Tasks
Imports System.Diagnostics
Imports IronPdf
Friend Class Program
	Public Shared Async Function Main() As Task
		Console.WriteLine("Generate PDF document Using IronPDF")
		Dim htmlToPdf = New ChromePdfRenderer()
		Dim content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>"
		For i As Integer = 0 To 9
			If i = 5 Then
				Continue For
			End If
			content &= $"<p>{i}</p>"
		Next i
		content &= "<h1>Generate Numbers from 1 to 10, stop at 7</h1>"
		For i As Integer = 0 To 9
			If i = 7 Then
				Exit For
			End If
			content &= $"<p>{i}</p>"
		Next i
		Dim pdf = htmlToPdf.RenderHtmlAsPdf(content)
		pdf.SaveAs("AwesomeIronPDF.pdf")
		Console.WriteLine("PDF generated successfully.")
	End Function
End Class
VB   C#

Code Explanation

  1. Initially, we are creating content to be used in a PDF document.
  2. We prepare the content as an HTML document.
  3. We use continue statement inside for loop to print from 1 to 10 and skip 5.
  4. Also, we use break statement to print from 1 to 7 and break.
  5. Then we use ChromePdfRenderer object to save the HTML document to a PDF document.

Output

C# Continue (How It Works For Developers): Figure 4 - Example output showcasing how continue and break method works

Best Practices and Considerations

  1. Clarity and Readability: In most cases, using structured control flow statements like break, continue, or nested loops can make your code more readable and understandable. The goto statements can make code harder to follow, especially for larger codebases or when used excessively.
  2. Avoiding Unintended Consequences: Misusing goto can lead to spaghetti code and make it difficult to reason about program behavior. It's essential to use goto judiciously and ensure that its usage is clear and well-documented.
  3. Error Handling: One common use case for goto is in error-handling scenarios, where it can be used to jump to a cleanup or error-handling routine. However, modern C# codebases often use structured exception handling (try-catch-finally) for error handling, which provides a more structured and readable approach.
  4. Performance Considerations: In terms of performance, goto generally has minimal impact. However, the primary concern with goto is maintainability and readability rather than performance.

License (Trial Available)

IronPDF.

A Trial Developer trial license is available here.

Please replace the Key in the appSettings.json file shown below.

{
  "IronPdf.License.LicenseKey" : "The Key Here"
}
{
  "IronPdf.License.LicenseKey" : "The Key Here"
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Conclusion

In conclusion, the continue and break methods are indispensable tools for controlling loop execution in C#. By strategically incorporating these statements into your code, you can enhance its efficiency, readability, and maintainability. While the goto statement in C# provides a mechanism for altering the flow of execution, its usage should be approached with caution. In most cases, structured control flow statements like break, continue, or nested loops offer clearer and more maintainable solutions. However, there are niche scenarios where goto can be used effectively and safely, such as in certain error-handling situations. As with any programming construct, it's crucial to weigh the trade-offs and consider the readability and maintainability of the code when deciding whether to use goto.

Together with IronPDF library from Iron Software to read and generate PDF documents, developers can gain advanced skills to develop modern applications.

< PREVIOUS
Html Agility Pack C# (How It Works For Developers)
NEXT >
Bugsnag C# (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >