Code Indentation and Comments

  • DO use default code editor setting provided by Microsoft Visual Studio.

    Auto format the code:

    • Visual Studio: Go to menu: Edit ==Advanced > Format Document== or press Ctrl+K,Ctrl+D
    • Visual Studio Code: Press Ctrl+Alt+F
  • DO remove and sort using import.

    • Visual Studio: ==Right-click > Remove & Sort Usings== or press Ctrl+R,Ctrl+G
  • DO write only one statement and declaration per line.

  • DO add one blank line space between each method.

  • DO use parentheses to understand the code written.

  • DO use xml commenting to describe functions, class and constructor.

  • DO use Tab for indentation.

  • DO use one blank line to separate logical groups of code.

  • DO use #region and #endregion to group related piece of code.

  • DO use // or /// for comments avoid using /* … */

  • ✅ If you have to use some complex for any reason, document it very well with sufficient comments.

  • ✅ If all variables and method names are meaningful, that would make the code very readable and will not need many comments.

  • ✅ For function definitions and calls, if the arguments do not all fit on one line they should be broken up onto multiple lines, with each subsequent line aligned with the first argument. If there is not enough room for this, arguments may instead be placed on subsequent lines with a four space indent. The code example below illustrates this.

    public int CalculateValue(int mulNumber) {
        // ...
    }
    
    // If possible, wrap arguments by aligning newlines with the first argument.
    public void AVeryLongFunctionNameThatCausesLineWrappingProblems(int longArgumentName,
                                                            int p1, int p2)
    {
    
    }
    
    // If aligning argument lines with the first argument doesn't fit, or is difficult to
    // read, wrap all arguments on new lines with one less more the current indentation.
    public void AnotherLongFunctionNameThatCausesLineWrappingProblems(
        int longArgumentName, int longArgumentName2, int longArgumentName3)
    {
    
    }
    
  • ✅ When using labels (for goto), indent the label one less than the current indentation.

  • ✅ When using a single-statement if, follow these conventions:

    • Never use single-line form.

      // Avoid
      if (source == null) throw new ArgumentNullException("source");
      
    • Using braces is always accepted, and required if any block of an if/else if/…​/else compound statement uses braces or if a single statement body spans multiple lines.

    • Braces may be omitted only if the body of every block associated with an if/else if/…​/else compound statement is placed on a single line.

  • DO NOT write comments for every line of code and every variable declared.

Learn More