Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
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 - a robust C# PDF library from Iron Software to read and write PDF documents.
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.
continue;
continue;
continue
public class Program
{
public static void Main()
{
Console.WriteLine("Demonstrate Continue Method in C#");
Console.WriteLine("Print 1 to 10 skipping 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 skipping 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 skipping 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
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 proceeds to the next iteration.
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.
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
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.
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.
The syntax of the goto statement in C# is straightforward:
goto label;
goto label;
GoTo label
Where the label is an identifier followed by a colon (:), indicating the target location in the code.
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.")
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.
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:
Now that we are aware of the IronPDF library, let us write an application to use IronPDF and continue statement, break statement, and goto Statement.
First, let's create a Visual Studio console application.
Provide the project name and location.
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
Now let us generate a PDF document using the control statements.
using System;
using System.Threading.Tasks;
using IronPdf;
class Program
{
public static async Task Main()
{
Console.WriteLine("Generate PDF document Using IronPDF");
// Initialize a ChromePdfRenderer to render HTML content to PDF
var htmlToPdf = new ChromePdfRenderer();
var content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>";
// Use continue statement to build HTML content
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
continue; // Skip appending number 5 to the content
}
content += $"<p>{i}</p>";
}
content += "<h1>Generate Numbers from 1 to 10, stop at 7</h1>";
// Use break statement to terminate loop at 7
for (int i = 0; i < 10; i++)
{
if (i == 7)
{
break; // Stop appending numbers after 6
}
content += $"<p>{i}</p>";
}
// Render the HTML content as a PDF document
var pdf = await htmlToPdf.RenderHtmlAsPdfAsync(content);
pdf.SaveAs("AwesomeIronPDF.pdf");
Console.WriteLine("PDF generated successfully.");
}
}
using System;
using System.Threading.Tasks;
using IronPdf;
class Program
{
public static async Task Main()
{
Console.WriteLine("Generate PDF document Using IronPDF");
// Initialize a ChromePdfRenderer to render HTML content to PDF
var htmlToPdf = new ChromePdfRenderer();
var content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>";
// Use continue statement to build HTML content
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
continue; // Skip appending number 5 to the content
}
content += $"<p>{i}</p>";
}
content += "<h1>Generate Numbers from 1 to 10, stop at 7</h1>";
// Use break statement to terminate loop at 7
for (int i = 0; i < 10; i++)
{
if (i == 7)
{
break; // Stop appending numbers after 6
}
content += $"<p>{i}</p>";
}
// Render the HTML content as a PDF document
var pdf = await htmlToPdf.RenderHtmlAsPdfAsync(content);
pdf.SaveAs("AwesomeIronPDF.pdf");
Console.WriteLine("PDF generated successfully.");
}
}
Imports System
Imports System.Threading.Tasks
Imports IronPdf
Friend Class Program
Public Shared Async Function Main() As Task
Console.WriteLine("Generate PDF document Using IronPDF")
' Initialize a ChromePdfRenderer to render HTML content to PDF
Dim htmlToPdf = New ChromePdfRenderer()
Dim content = "<h1>Generate Numbers from 1 to 10, skip 5</h1>"
' Use continue statement to build HTML content
For i As Integer = 0 To 9
If i = 5 Then
Continue For ' Skip appending number 5 to the content
End If
content &= $"<p>{i}</p>"
Next i
content &= "<h1>Generate Numbers from 1 to 10, stop at 7</h1>"
' Use break statement to terminate loop at 7
For i As Integer = 0 To 9
If i = 7 Then
Exit For ' Stop appending numbers after 6
End If
content &= $"<p>{i}</p>"
Next i
' Render the HTML content as a PDF document
Dim pdf = Await htmlToPdf.RenderHtmlAsPdfAsync(content)
pdf.SaveAs("AwesomeIronPDF.pdf")
Console.WriteLine("PDF generated successfully.")
End Function
End Class
continue
: In the first loop, we use the continue statement to skip number 5 when generating numbers from 1 to 10.break
: In the second loop, we use the break statement to stop the loop once the number 7 is reached.ChromePdfRenderer
object to convert the HTML content to a PDF file and save it.Explore IronPDF Licensing Details.
A Trial Developer trial license is available Get a Trial License.
Please replace the Key in the appSettings.json file shown below.
{
"IronPdf.License.LicenseKey": "The Key Here"
}
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 - Comprehensive PDF Solutions library from Iron Software, developers can gain advanced skills to develop modern applications.
The 'continue' statement in C# is used within loop structures to skip the remaining code block and proceed to the next iteration of the loop. It helps in skipping the current iteration's remaining code and moving on to the next iteration.
The 'break' statement in C# is used to exit a loop prematurely. When encountered, it terminates the loop's execution, stopping the loop regardless of the loop's condition.
While 'goto' can be powerful, it is often discouraged in modern programming practices due to potential readability and maintainability issues. It should be used judiciously, primarily in scenarios like specific error-handling situations, and always with clear documentation.
A comprehensive PDF library like IronPDF allows developers to create, edit, and manipulate PDF documents. It offers features like HTML to PDF conversion, PDF editing, cross-platform support, and compatibility with various .NET versions.
Yes, the 'continue' statement can be used in loops to skip certain iterations, which can help in selectively adding content to a PDF during its generation, as demonstrated with IronPDF.
The primary concern with 'goto' is maintainability and readability rather than performance. It generally has a minimal impact on performance, but it's crucial to use it carefully to avoid making the code difficult to follow.
In PDF generation with a library like IronPDF, the 'break' statement can be used to stop loops at a specific condition, thus controlling the content that is added to the PDF, such as stopping the addition of numbers after a certain point.
A comprehensive PDF library like IronPDF is compatible with various .NET versions, including .NET Core, .NET Standard, and .NET Framework. It supports C#, VB.NET, F#, and is available for Java, Node.js, and Python. It also integrates with IDEs like Microsoft Visual Studio and JetBrains Rider.
The syntax for the 'goto' statement in C# is 'goto label;', where the label is an identifier followed by a colon (:), representing the target location in the code where control is transferred.
To install a comprehensive PDF library like IronPDF in a C# project, you can use the command 'dotnet add package IronPdf --version [version_number]' in your development environment, such as Visual Studio.