Share via


Who'da thunk it? #1

This is the first in an ongoing series on the non-obvious (to me, at least).

This question is from an internal mailing list. Should the following C# code compile?

     
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            goto exit;
            exit:
        }
    }
}
    
    

My intial reaction was "Of course!" However, I was wrong. The compiler reports the following errors:
Error 1 Invalid expression term '}' line 13 column 9
Error 2 ; expected line 13 column 10

According to section 8.9.3 of the C# spec, "the target of a goto identifier statement is the labeled statement with a given label." Note that the target is a labeled statement, not an identifier. Since the smallest statement that qualifies as a labeled statement is the empty statement (a semicolon by itself), the label must be followed by at least a semi-colon to compile.  So the correct code would be: 

     
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            goto exit;
            exit:;
        }
    }
}
    
    

Who'da thunk it?
~Dan