Showing posts with label quiz. Show all posts
Showing posts with label quiz. Show all posts

Friday, April 2, 2010

Quiz #2 - The answer (goto in c#)

@YaronNaveh

A few days ago I published the below reflector generated code:


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


And asked what was the original code. Well, here it is:



void NoGoTo()
{
        int i = 0;
        if (i==0)
        {
            switch (i)
            {
                case 0:
                    break;
                case 1:
                    break;
                default:
                    i-- ;
                    break;
            }
        }

        i++;
}


no goto at all.

Liran and an anonymous reader corresponded that goto may not be that bad in all cases. They are right, loop controls such as break and continue are disguised goto's. Liran also mentioned the multi-level breaks in Java which satisfy some of the goto possible use cases. For me all of these are an attempt to capture the 'good' goto use cases and keep our code clean from possible abuse of the generic flavor.

My motivation for the whole inquiry was seeing a lot of goto's in framework code using the reflector. One example is BasicHttpMessageSecurity.CreateMessageSecurity(). I wanted to make sure I am up to the times with the latest coding fashions. When I have downloaded the WCF sources locally to debug them I no no sign of goto.

@YaronNaveh

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

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!