Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

The goto-less goto!

3.25/5 (4 votes)
24 Jan 2011CPOL 10.8K  
I'm a C# programmer. I try to avoid goto at all costs, and generally I try to avoid throwing exceptions for the purpose of controlling the flow of execution. I've always been of the opinion that exceptions are for exceptional situations and indicate errors rather than expected conditions.I...
I'm a C# programmer. I try to avoid goto at all costs, and generally I try to avoid throwing exceptions for the purpose of controlling the flow of execution. I've always been of the opinion that exceptions are for exceptional situations and indicate errors rather than expected conditions.

I suggest encapsulating this sort of code in its own method. You can just return from the method early if one of the goto conditions is met.

public void SomeMethod()
{
    MethodThatReturnsEarlyIfCertainConditionsAreMet();
}

private void MethodThatReturnsEarlyIfCertainConditionsAreMet()
{
    // Using a random number is for illustrative purposes only;
    // in a real situation you might be testing some other kind
    // of value set elsewhere in the code or whatever.
    Random random = new Random();
    int i = random.Next(10);

    if (i < 10) return; // early return; our condition was met.

    DoOtherWork();

    i = random.Next(10);

    if (i < 5) return; // early return; a different condition was met.

    DoMoreOtherWork();

    // etc.
}


While I like the idea of all methods having only one return, in practice I don't feel that it's worth it, especially for situations like this.

I don't know how this sort of thing would behave in C++, but I know in C#, the CLR would handle cleanup of your locals when the method returns, which ultimately includes calling destructors if they are used, though Microsoft's recommendation in .NET languages is to implement IDisposable when you have unmanaged resources to clean up.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)