Remember goto? If you are young enough, you may not. The goto statement does exactly what it says, moving code execution to name position. In one of my first C/C++ classes in college, using a goto statement meant an automatic F for the assignment. This is because goto makes code very hard to read. It is hated for a good reason. Decision statements like if/else and switch are much better choices.
Today I learned a good use of goto that actually make code more readable.
In C#, the switch() statement does not allow case fall-through. Consider the following example in C:
switch(someIntValue)
{
case 1:
printf(“Found case 1!\n”);
case 2:
printf(“Found case 2!\n”);
case 3:
printf(“Found case 3!\n”);
case 4:
printf(“Found case 4!\n”);
break;
}
If someIntValue equals 2, this would print:
Found case 2!
Found case 3!
Found case 4!
In C#, this does not work. The developers of C# chose to not allow fall-through for better code readability or code maintainability. To allow an equivalent functionality in C#, use goto:
switch(someIntValue)
{
case 1:
Console.WriteLine(“Found case 1!\n”);
goto case 2;
case 2:
Console.WriteLine(“Found case 2!\n”);
goto case 3;
case 3:
Console.WriteLine(“Found case 3!\n”);
goto case 4;
case 4:
Console.WriteLine(“Found case 4!\n”);
break;
}
In this example, goto actually makes the code more readable and more maintainable by making the fall-through explicit instead of implicit. I have been programming C# since 2001, and I did not know this existed until today. Very cool.
