Monday, March 29, 2010

Quiz #2: Goto statement in C#

@YaronNaveh

I have written a very simple C# method. This method did not contain any goto statements (they're bad, right?). I have then opened my method in the reflector and found this:


private void NoGoto()
{
     int i = 0;
     if (i == 0)
     {
         switch (i)
         {
             case 0:
             case 1:
             goto Label_002C; //WTF?!
         }
         i--;
     }
    Label_002C:
         i++;
}


The quiz question is: What is going on here? What was my original code?

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

5 comments:

Anonymous said...

Goto isn't bad if you know how to use it.

Read here: http://www.scipio.org/Courses/OS_course/Pages/goto.html

Yaron Naveh (MVP) said...

Thanks for the link. I agree that in some cases goto may make sense but I haven't seen yet a case where you cannot write cleaner code using other language features.

Liran said...

goto statements aren't necessarily evil. actually, sometimes they prove to be quite useful:

http://blogs.microsoft.co.il/blogs/liran_chen/archive/2010/03/20/demystifying-goto-evilness.aspx

Yaron Naveh (MVP) said...

Hi Liran

I actually like the Java approach of multi-level breaks. Instead of a coarse-grained goto statement (which can be wrongly or rightly used) it introduces a new language feature that supports only the "good" subset of goto. Very similar to "break" or "continue" which also cover subset of the goto usage.

Unknown said...

GO statement was good for structural programming. It doesn't make sense to use it (except in special cases) in OOP.