#966 – Visual Studio Code Editor Helps with Indenting

You’ll typically use a consistent indent level in your source code to assist with readability.  Visual Studio helps by automatically indenting your code as you enter it.

For example, if you enter an if statement and then press Enter to move to the next line, Visual Studio automatically indents the then portion of the if statement.

966-001

You can change the indent level by:

  • Selecting Tools | Options
  • Navigating to Text Editor | C# | Tabs
  • Changing the value in the Indent size field  (default is 4)

966-002

Note that the default is to insert a series of spaces when the Tab key is pressed.

You can easily re-format a document to match the requested indent level.  For example, assume that we start with some non-indented code:

966-003

You can indent the entire document by selecting Edit Advanced Format Document.  The document will be re-formatted using the current indent level.

966-004

#965 – Indent Code to Improve Readability

The C# compiler doesn’t care how consecutive statements in your source code are indented, or even whether they appear on one or on multiple lines.

For clarity, it’s customary to indent blocks of code to show visually that the code is within the scope of an outer block or statement.  Four spaces are typically used as an indent.  (Some people use TABs instead of spaces, but TABs are often displayed differently, depending on the editor and can make it difficult to change the indent level of a line).

Below is an example of code that uses indents with four spaces.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Test(3);

            Console.ReadLine();
        }

        // Comment goes here
        static void Test(int i)
        {
            int twice = 2 * i;

            Console.WriteLine(i);
            if (i > 2)
                Console.WriteLine("not tiny");

            if (DateTime.Now.DayOfWeek == DayOfWeek.Thursday)
            {
                Console.WriteLine("Today is Thursday");
                Console.WriteLine("Eat {0} hamburgers", twice);
            }
        }
    }
}