Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should empty "if" statement in C# lead to an error or warning?

Let me start from a real life example:

Customer: Alex, just noticed something strange in the RemovalProcessor at line 138:

if (Session.Handler.ExecutePrefetchTasks()==null); 
  Session.ExecuteDelayedQueries(); 

Should the semicolumn behind the 'if' be there?

Me: Oops... I'll send this to our guys to check, but most likely, you're right.

Although the case is rare, I admit nearly any big project has similar issue.

I understand that semicolon (and statement block) usage rules in C# can't be changed (personally I'd prefer Python style). But I think it's a good idea to identify exactly this case with if statement, and classify it as an error or warning.

Few Q/A I have in mind:

  • Why warning or error should be generated in this case?

    Because it's a developer's mistake with may be 99% probability.

  • Why error is preferable in this case?

    In many cases warnings are ignored by developers.

    I understand this is their own problem, and there is /warnaserror (threat warnings as errors) switch, but since this is an error with very high probability, and, if it isn't an error (really? ;) ), it's quite easy to fix this, may be it's better to classify this case as an error.

    Finally, error in this case won't "restrict" the developer, since such code can (and likely, must) always be rewritten without if statement.

  • Why warning is preferable in this case?

    This won't break the compatibility; I also suspect some code generators may generate code relying on the current behavior.

So I'd be glad to hear your opinions about this.

like image 983
Alex Yakunin Avatar asked Dec 12 '22 20:12

Alex Yakunin


1 Answers

It already produces a warning:

Possible mistaken empty statement

I agree with you that an error would have been preferable (if you really want an empty statement, can always write it as { }, which is more explicit) — but they are not going to change the C# language in this way. It would be a breaking change, and I suspect their (read: Eric Lippert’s) justification will be “the benefit doesn’t outweigh the cost”.

like image 152
Timwi Avatar answered Jan 19 '23 00:01

Timwi