c# – Empty semicolon does not give an error?

Question:

I was working on a project and I accidentally bumped into the semicolon that ended up being inserted right after an if . I was intrigued because Visual Studio did not point out as an error, and when I tried to compile the project I was successful.

The code looked like this:

if(alguma_coisa)
{
   //Bloco lógico
};

Out of curiosity, I realized that it's also possible to insert a semicolon at the end of loops like while , for and foreach .

I showed it to a friend and he revealed the possibility of inserting the semicolon several times in a row on the same line as follows:

if(alguma_coisa)
{
   //Bloco lógico
}; ; ; ; ; ;

And yet the project compiles without any problems.

Shouldn't a compilation error be generated?
Why is this allowed?

Answer:

The semicolon serves to determine the end of an instruction. What happens in this case is that "the instruction" does nothing.

Do that:

if(true)
{
};

it's the same thing as doing

if(true)
{    
}
; //Final da "instrução" que está vazia
Scroll to Top