Statements
In this lesson, we will discuss the writing style one should follow while working with the statements in C#.
Simple Statements
Each line should contain only one statement.
Return Statements
A return
statement should not use outer most parentheses.
Avoid:
return (n * (n + 1) / 2);
Use:
return n * (n + 1) / 2;
If Statements
if
, if-else
and if else-if else
statements should look like this:
if:
if (condition) {
DoSomething();
...
}
if-else:
if (condition) {
DoSomething();
...
} else {
DoSomethingOther();
...
}
if else-if else:
if (condition) {
DoSomething();
...
} else if (condition) {
DoSomethingOther();
...
} else {
DoSomethingOtherAgain();
...
}
For / Foreach Statements
A for
statement should have following form:
for (int i = 0; i < 5; ++i) {
...
}
A foreach
should look like :
foreach (int i in IntList) {
...
}
Note: Generally use brackets even if there is only one statement in the loop.
While/Do-While Statements
A while
statement should be written as follows:
while (condition) {
...
}
A do-while
statement should have the following form:
do {
...
} while (condition);
Switch Statements
A switch
statement should be of following form:
switch (condition) {
case A:
...
break;
case B:
...
break;
default:
...
break;
}
Try-Catch Statements
A try-catch
statement should follow this form:
try {
...
} catch (Exception) {}
or
try {
...
} catch (Exception e) {
...
}
or
try {
...
} catch (Exception e) {
...
} finally {
...
}