Search code examples
c#.netgotocode-structure

Using a Goto to enhance the DRY principle and code clarity: a good idea?


I have some code that is structured like the following:

if (someStatement)
{
    //...
    if (SomeOtherStatement)
    {
        //..., possibly more cases like this
    }
    else
    {
        //goto warning;
        //would otherwise repeat
        //the MessageBox.Show here
    }
}
else
{
    //goto warning;
}
//...
warning:
MessageBox.Show("some warning");

As i abhor copying code, is this one of the few useful applications of goto or is there a better structure i can use?


Solution

  • What about this?

    if (someStatement)
    {
        //...
        if (SomeOtherStatement)
        {
            //..., possibly more cases like this
    
            return; // in the inner-most case
        }
    }
    
    MessageBox.Show("some warning");