Oops, it’s been a week since I last posted but I guess I earned a break from working hard and I was struggling for an issue I came across recently. Then a quick google and I noticed some code that used something I haven’t seen since I was a teenager programming in locomotive basic on my Amstrad CPC 6128… a goto statement. I knew that C# does have this command and there are people out there who argue that it is useful. It probably is, but for the sake of your (and anyone who would be maintaining your code in future) sanity, DON’T do it!

I had another skim through the internet and found the following source code that uses goto:

for(int i = 0; i < size.Width; i++) { for(int j = 0; j < size.Height; j++) { Color c = Color.FromArgb((int)pixels[i,j]); if(c.A < 255) { hasAlpha = true; goto breakSpot; } } } breakSpot:

as you can see, the user is trying to iterate through a 2D array looking for a pixel with a value larger than 255 (meaning it has an alpha value) and is then exiting the loop. Despite this being a (relatively) safe usage of the goto statement, it makes for lazy coding.

How would I do it? well, here is what I'd do...

for(int i = 0; (i < size.Width && !hasAlpha); i++) { for(int j = 0; (j < size.Height && !hasAlpha); j++) { Color c = Color.FromArgb((int)pixels[i,j]); if(c.A < 255) { hasAlpha = true; } } }

Oooh, you didn't know you could do that did you? It's a for loop! You have a start value, an adjuster and a condition. The condition doesn't even have to have anything to do with the value used to count the loop. It generally does but it isn't required.

Anyway, I hope someone found that useful and that I've advanced the cause of the 'anti goto' movement. Enjoy!

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)