What does a semi colon do after a conditional block in C#?

  • A+
Category:Languages

I recently came across this code in a project - which I assume was there by mistake:

if(condition) {    //Whatever... }; 

Note the semi colon after the closing brace.

Does anyone know what the effect of this is?

I assume it does not have any effect, but would have thought it would have caused a compiler error

 


This is a simple question with a simple answer but I just wanted to add something. Often people understand that it does nothing.

But what is the rationale behind it ?

Actually, those empty statements are allowed for statement like these:

 // Use an empty statement as the body of the while-loop. while (Method())         ; 

I agree that it does nothing. But it can help certain loops conform to the syntactic requirements of the language and I think this is what people should understand from it. As other said, I agree you can remove it, I just wanted to underline why c# allows it.

Further clarification

An empty statement is used when you don't need to perform an operation where a statement is required. It simply transfers control to the end point of the statement. It has no effect at all, it is pure syntactic sugar.

As stated by @PaulF, in the example above, you could use an empty block ({}) instead. It would be totally valid and have the same effect.

Again, it all comes down to style. You don't need it, but it can certainly help you conform to whatever rules of your coding environments.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: