Labels with C#
In C#, "labels" generally refer to identifiers used to mark a specific point in the code that can be the target of a jump or branch operation. Labels are typically used in conjunction with control flow statements such as goto, break, and continue.
Below are some examples where the labels in c# might be useful. However, before you go ahead and use them, please always make sure to run them by your team, as it is a matter of preference and some people may really not like it!
Labels in a switch statement:
public static void SwitchGoToExample(string name)
{
switch (name)
{
case "c#":
Console.WriteLine("Name is c#");
goto case "csharp#";
case "C#":
Console.WriteLine("Name is C#");
break;
case "csharp#":
Console.WriteLine("Name is csharp");
break;
default:
Console.WriteLine("Not a match");
break;
}
}
HttpClient request retry:
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class RetryRequest
{
private const int MaxRetryAttempts = 3;
public static async Task Main()
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = null;
int attempt = 0;
retry: // this is our label targeting the retry section of the program
try
{
response = await httpClient.GetAsync("http://example.com");
if(!response.IsSuccessStatusCode)
throw new HttpRequestException();
}
catch(Exception)
{
if (++attempt == MaxRetryAttempts)
throw; // re-throw exception if max attempts reached
await Task.Delay(TimeSpan.FromSeconds(attempt)); // wait before retrying
goto retry; // here we redirect code execution to the "retry" label
}
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}
Infinite loop (throw an exception and recover):
public static void InfiniteLoopWithLabels()
{
var counter = 0;
ThreadStart:
try
{
if (counter == 2)
{
throw new Exception("Reset");
}
counter++;
Console.WriteLine("Counter is: {0}", counter);
goto ThreadStart;
}
catch (Exception e)
{
Console.WriteLine("Counter will reset");
counter = 0;
goto ThreadStart;
}
}
No files yet, migration hasn't completed yet!