...

/

Indentation

Indentation

In this lesson, we will learn how to indent a C# code.

Wrapping Lines

When an expression will not fit on a single line, break it up according to these general principles:

  • Break after a comma.
  • Break after an operator.
  • Prefer higher-level breaks to lower-level breaks.
  • Align the new line with the beginning of the expression at the same level on the previous line.

Example of breaking up method calls:

Press + to interact
longMethodCall(expr1, expr2,
expr3, expr4, expr5);

Examples of breaking an arithmetic expression:

Press + to interact
// PREFER:
var = a * b / (c - g + f) +
4 * z;
// BAD STYLE – AVOID:
var = a * b / (c - g +
f) + 4 * z;

The first is preferred, since the break occurs outside the paranthesized expression (higher level rule).

White Spaces

An indentation standard using spaces never was achieved. Some people like 2 spaces, some prefer 4 and others die for 8, or even more spaces. Better use tabs. Tab characters have some advantages:

  • Everyone can set their own preferred indentation level.
  • It is only 1 character and not 2, 4, 8 … therefore it will reduce typing (even with smart-indenting you have to set the indentation manually sometimes, or take it back or whatever).
  • If you want to increase the indentation (or decrease), mark one block and increase the indent level with Tab with Shift-Tab you decrease the indentation.

Here, we define the Tab as the standard indentation character:

Don’t use spaces for indentation - use tabs!