C# Break Statement
Here are C# and VB.net example of using For loop break statement and Foreach loop break statement. Let's see how to break loop and avoid further iterations.
Remember: You can only break or continue loops. You can’t break the function or stop program executing something. The keyword break is used with C# for loop and foreach loop.
To skip the current iteration, you can use continue statement instead of break statement.
Let’s see how to use break statement examples in C# and VB.net.
C# Break statement foreach loop.
using System;
namespace Csharp.BreakStatement
{
class Program
{
static void Main(string[] args)
{
string[] arrString = new string[] { "First", "Second", "Third", "Fourth" };
foreach (string s in arrString)
{
if (s == "Third")
break;
else
Console.WriteLine(s);
}
Console.WriteLine();
}
}
}
Vb.net break statement foreach loop example.
Imports System
Namespace Csharp.BreakStatement
Class Program
Private Shared Sub Main(args As String())
Dim arrString As String() = New String() {"First", "Second", "Third", "Fourth"}
For Each s As String In arrString
If s = "Third" Then
Exit For
Else
Console.WriteLine(s)
End If
Next
Console.WriteLine()
End Sub
End Class
End Namespace
C# break for loop
Here are C# and Vb.net break statement using for loop example. At the end of this post you can see the output of all programs.
C# break for loop example
using System;
namespace Csharp.BreakStatement
{
class Program
{
static void Main(string[] args)
{
string[] arrString = new string[] { "First", "Second", "Third", "Fourth" };
for(int i=0; i < arrString.Length ; i++)
{
if (arrString[i] == "Third")
break;
else
Console.WriteLine( arrString[i] );
}
Console.ReadLine();
}
}
}
VB.net break statement using for loop example.
Imports System
Namespace Csharp.BreakStatement
Class Program
Private Shared Sub Main(args As String())
Dim arrString As String() = New String() {"First", "Second", "Third", "Fourth"}
For i As Integer = 0 To arrString.Length - 1
If arrString(i) = "Third" Then
Exit For
Else
Console.WriteLine(arrString(i))
End If
Next
Console.ReadLine()
End Sub
End Class
End Namespace
Output
First
Second
Description
As you can see the output of above programs. The loop breaks on the occurrence of condition.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5