C# Language goto

Download C# Language for free

Example

goto can be used to jump to a specific line inside the code, specified by a label.

goto as a:

Label:

void InfiniteHello()
{
    sayHello:
    Console.WriteLine("Hello!");
    goto sayHello;
}

Live Demo on .NET Fiddle

Case statement:

enum Permissions { Read, Write };

switch (GetRequestedPermission())
{
    case Permissions.Read:
        GrantReadAccess();
        break;

    case Permissions.Write:
        GrantWriteAccess();
        goto case Permissions.Read; //People with write access also get read
}

Live Demo on .NET Fiddle

This is particularly useful in executing multiple behaviors in a switch statement, as C# does not support fall-through case blocks.

Exception Retry

var exCount = 0;
retry:
try
{
    //Do work
}
catch (IOException)
{
    exCount++;
    if (exCount < 3)
    {
        Thread.Sleep(100);
        goto retry;
    }
    throw;
}

Live Demo on .NET Fiddle

Similar to many languages, use of goto keyword is discouraged except the cases below.

Valid usages of goto which apply to C#:

  • Fall-through case in switch statement.

  • Multi-level break. LINQ can often be used instead, but it usually has worse performance.

  • Resource deallocation when working with unwrapped low-level objects. In C#, low-level objects should usually be wrapped in separate classes.

  • Finite state machines, for example, parsers; used internally by compiler generated async/await state machines.

if, if...else, if... else if