C# Keywords Tutorial Part 9: break

C# Keywords Tutorial Part 9: break

The most widely used programming language in the world among developers is C#. ‘break’ is one of the crucial keywords in C#. We will discuss the C# “break” keyword and give some code samples in this blog post.

What does the C# word “break” mean?

To end a loop or switch statement in C#, use the break keyword. It is frequently used to end a loop when a specific requirement is satisfied or to end a switch statement when a match is discovered. Your code will work better and be more efficient if you use the keyword “break.”

using the for loop’s break keyword

Let’s take a look at an example of how the ‘break’ keyword can be used in a for loop:

for (int i = 1; i <= 10; i++)
{
? ? if (i == 5)
? ? {
? ? ? ? break;
? ? }
? ? Console.WriteLine(i);
}        

In the above example, we have a for loop that will run from 1 to 10. However, we have added an ‘if’ statement inside the loop that checks whether the value of ‘i’ is equal to 5. If the condition is true, the ‘break’ keyword is executed, and the loop is terminated. As a result, the output of the above code will be:

1
2
3
4        

Using the ‘break’ keyword in a while loop

We can also use the ‘break’ keyword in a while loop. Here’s an example:

int i = 1;


while (i <= 10)
{
? ? if (i == 5)
? ? {
? ? ? ? break;
? ? }
? ? Console.WriteLine(i);
? ? i++;
}        

In this example, we use a while loop to print the values from 1 to 10. We have added an ‘if’ statement inside the loop that checks whether the value of ‘i’ is equal to 5. If the condition is true, the ‘break’ keyword is executed, and the loop is terminated. As a result, the output of the above code will be:

1
2
3
4        

Using the ‘break’ keyword in a switch statement

The ‘break’ keyword can also be used in a switch statement to exit the switch block when a match is found. Here’s an example:

int day = 4;


switch (day)
{
? ? case 1:
? ? ? ? Console.WriteLine("Monday");
? ? ? ? break;
? ? case 2:
? ? ? ? Console.WriteLine("Tuesday");
? ? ? ? break;
? ? case 3:
? ? ? ? Console.WriteLine("Wednesday");
? ? ? ? break;
? ? case 4:
? ? ? ? Console.WriteLine("Thursday");
? ? ? ? break;
? ? case 5:
? ? ? ? Console.WriteLine("Friday");
? ? ? ? break;
? ? default:
? ? ? ? Console.WriteLine("Weekend");
? ? ? ? break;
}        

In the above example, we have a switch statement that checks the value of the ‘day’ variable and prints the corresponding day of the week. If the value of ‘day’ is equal to 4, the ‘break’ keyword is executed, and the switch statement is terminated. As a result, the output of the above code will be:

Thursday        


要查看或添加评论,请登录

社区洞察

其他会员也浏览了