I have a piece of C# code in which I use the goto statement. Is this a correct use of the goto statement or is there a better alternative solution?
bool IsValid(TestObject aObject)
{
bool aRetVal = false;
if(condition here)
goto exit;
if(condition here)
goto exit;
if(condition here)
goto exit;
aRetVal = true;
exit:
return aRetVal;
}
The reason I’m doing this is because I don’t want multiple exit points in my method.
No – use
returninstead. Why force someone reading your code to skip to an exit point and then return? You know everything you need to do at this point – so the clearest solution is to return, IMO.The “don’t have multiple exit points” idea was appropriate in languages where you’d need to do things like cleanup on the exit of a function, but between garbage collection and
finallyblocks, it’s pointless and counterproductive in C#.What do you want to do if the condition is met? Return from the method. So make your code say that. Wherever you can make the code say exactly what you mean, that’s a good thing. Don’t make it more complicated than it needs to be.
I’m assuming your real situation is more complicated than just these conditions, otherwise I’d use something like Marcelo’s answer, but probably written as: