White Spaces
In this lesson, we will learn how to use white spaces to achieve a good formatting of a C# code.
Blank Lines
Blank lines improve readability. They set off blocks of code which are in themselves logically related. Two blank lines should always be used between:
- Logical sections of a source file.
- Class and interface definitions (try one class/interface per file to prevent this case).
One blank line should always be used between:
- Methods
- Properties
- Local variables in a method and its first statement
- Logical sections inside a method to improve readability
Note that blank lines must be indented as they would contain a statement this makes insertion in these lines much easier.
Inter-term spacing
There should be a single space after a comma or a semicolon, for example:
Use:
TestMethod(a, b, c);
Avoid:
TestMethod(a,b,c)
// OR
TestMethod( a, b, c );
Single spaces surround operators (except unary operators like increment or logical not), example:
Use:
a = b;
for (int i = 0; i < 10; ++i)
Avoid:
a=b;
for (int i=0; i<10; ++i)
for(int i=0;i<10;++i)
Table like formatting
A logical block of lines should be formatted as a table:
string name = "Mr. Ed";
int myValue = 5;
Test aTest = Test.TestYou;
Use spaces for the table like formatting and not tabs because the table formatting may look strange in special tab intent levels.