What is better coding practice for single-line code blocks following an if statement - braces or no braces? Just to avoid too many "Well, it depends on what language you're using..." answers, let's say for C#. In other words, which is better:
if(somecondition)
{
singleLineStatement;
}
Or
if(somecondition)
singleLineStatement;
90) Can the curly brackets { } be used to enclose a single line of code? While curly brackets are mainly used to group several lines of codes, it will still work without error if you used it for a single line.
However it is highly recommended that you always use braces because if you (or someone else) ever expands the statement it will be required. This same practice follows in all C syntax style languages with bracing. C, C++, Java, even PHP all support one line statement without braces.
If the true or false clause of an if statement has only one statement, you do not need to use braces (also called "curly brackets"). This braceless style is dangerous, and most style guides recommend always using them.
In the first case, the Line1 and Line2 both are in the if block. But in the second condition, the Line1 is in if block but Line2 is not in if block. So we can omit curly braces only there is a single statement under if-else or loop.
I think the consensus is to use braces. If you omit the braces there is a risk that someone will add an extra line without noticing the missing braces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With