65.9K
CodeProject is changing. Read more.
Home

The goto-less goto!

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jan 31, 2011

CPOL
viewsIcon

6910

In C#, you can always use try..finally to add some finalization code.Just write:bool bFailed = true; try{ if(condition1_fails) return; ... if(condition2_fails) return; ... ... if(conditionN_fails) ...

In C#, you can always use try..finally to add some finalization code. Just write:
bool bFailed = true;  
try
{
     if(condition1_fails)     
          return;  
     ...  
     if(condition2_fails)     
          return;  
     ...  
     ...  
     if(conditionN_fails)     
          return;  
     bFailed=false;  
     PerformActionOnAllSuccess();
}
finally
{
     if(bFailed)     
          DoFailedCleanup();  
     else     
          DoNormalCleanup();
}
But I don't think it's a good practice. We shouldn't use goto not because it's an ugly word. We shouldn't use goto because its behavior implies poor code readability, and all alternatives that just change the words, but not the bad behavior, should be avoided.