#975 – Guidelines for Commenting Your Code

The primary goal of including comments in your code is to make the code + comments self-documenting enough that a developer other than the original author can understand what the code does and how it does it.

Guidelines for well commented code include:

  • Wherever possible, the code should “self document”:
    • Meaningful names for variables and methods
    • Consistent layout
    • Modularized code — each method performs a single task
    • Minimize nesting, where possible
  • Write effective comments:
    • Don’t just repeat what the code does
    • Use a comment to summarize a block of code that follows the comment, providing a high-level description of what the code does
    • Describe what and why, rather than how.  The code describes how and sometimes what.  Comments add to the what and also talk about why.
    • Modify comments when you modify code, if appropriate (i.e. keep the comments current)
    • Don’t comment tricky code–rewrite the code
    • Write for humans

#974 – Well Written Code Includes Well Written Comments

Well written code includes well written comments.  Including comments that help explain what the code is doing is part of the process of writing high quality source code.

The main goal of well commented code is to make the code easier to maintain.  Software that goes into production often ends up being used for many years.  This means that the amount of money spent maintaining the software can be far greater than the amount spent to develop the software.  During development, anything that you can do to make maintaining the software easier is a good investment.

Comments should not merely parrot back what the code is doing.

            // Add two to the age
            age += 2;

Instead, good comments provide more information than is possible by reading the code.

            // As part of calculating longevity, adjust for being a smoker.
            // See http://somepeerreviewestudyonsmoking.com
            if (theCustomer.IsSmoker())
                predictedMaxAge += 2;

#973 – Format Items in Composite Format Strings Can Be in Any Order

A composite format string contains some combination of actual text and format items that will be substituted with values of corresponding placeholders at run-time.

For example:

            string name = "Sean";
            int age = 49;

            Console.WriteLine(string.Format("{0} is {1} yrs old. {0} is old.", name, age));


A format item is indicated by a 0-based index within a pair of braces. Notice that you can have multiple format items that refer to the same placeholder.

You can also include the format items in any order.  At run-time, each format item is evaluated and the appropriate value is substituted.

            Console.WriteLine(string.Format("Age: {1}, Name: {0}.  {1} {1} {1}..", name, age));


#972 – Reading Keystrokes from the Console

The Console.Read method reads input from a console window one character at a time but does not begin reading characters until after the user has pressed Enter.

The Console.ReadKey method, on the other hand, reads a key that the user presses immediately, without waiting for the user to press Enter.  The ReadKey method returns a value whose type is ConsoleKeyInfo, which contains fields that tell you which key was pressed:

  • Key field – ConsoleKey (enumeration) value indicating the exact key that was pressed
  • KeyChar field – Unicode character (of type char) for the key that was pressed

In the example below, we read two keypresses before displaying what was entered.  Notice that the output is shown after we enter two characters, but before we’ve pressed the Enter key.

            ConsoleKeyInfo cki1 = Console.ReadKey();
            ConsoleKeyInfo cki2 = Console.ReadKey();



#971 – Reading a Line of Input from the Console

For testing purposes, you may create a simple console application that allows writing to and reading from a console window.

The Console.ReadLine method reads the next line’s worth of characters, storing the result in a string.  The user can enter some text and then press the Enter key.  When the user presses Enter, whatever they typed on that line is stored in a variable of type string.

            while (true)
                Console.Write(": ");
                string nextLine = Console.ReadLine();

                Console.WriteLine("[{0}]", nextLine);


You can also use the Console.Read method to read a single character. The characters are not read until the user presses Enter.

In the example below, the user types the letters a, and and then presses Enter.  The two calls to Console.Read are then executed, storing the ASCII values of the characters entered.

            int char1 = Console.Read();
            int char2 = Console.Read();

            Console.Write("{0} {1}",


#970 – Checking for Valid Characters in a String

You can use a regular expression to check a string to see if the string contains only characters within a specified set of characters.

For example, to check whether a string is limited to a single line containing only alphabetic characters (e.g. a..z, A..Z), you can use the regular expression shown below.

        private bool IsAlphabetic(string s)
            Regex r = new Regex(@"^[a-zA-Z]+$");

            return r.IsMatch(s);

The regular expression defines a pattern and the IsMatch method checks the string to see if it matches the pattern.  You can read the regular expression as follows:

  • ^ – start of the string
  • [a..zA..Z] – single character that is a lowercase or uppercase letter
  • + – repeat previous item one or more times (alphabetic character)
  • $ – end of the string

A string will therefore match if it is a single line of text containing at least one alphabetic character and is limited to alphabetic characters.



#969 – Creating a Simple Console Application

You’ll most often create applications that have some sort of user interface, e.g. web applications, Windows Store apps, or desktop applications.  You may also create components using C# that have no user interface at all, e.g. class libraries.

For testing purposes, however, it’s helpful to create a simple application that can read from or write to a console window.  The console window appears as a window with a dark background when you run the application.  It can display text one line at a time, or read text entered by the user.  As new text is added to the bottom of the window, earlier text scrolls off the top.


You create a console application using Visual Studio by selecting the Console Application template when creating a new project.


You read from or write to the console using methods in the Console class, e.g. ReadLine and WriteLine.

#968 – Reading a Value from a Variable

Once you’ve assigned a value to a variable, you can read the value back.  You can use the variable name anywhere that a value of the appropriate type is expected.

            // Assign value to int variable
            int n = 5;

            // Read value from variable n and use it in an expression
            int result1 = n * 2;

            string info = string.Format("n={0}, result1={1}", n.ToString(), result1.ToString());


#967 – Assigning a Value to a Variable

You store a value in a variable, or assign the value, use the = operator.  The = operator is known as the simple assignment operator.

When using the simple assignment operator, the value of the right operand is computed and the result is stored in the variable that appears as the left operand.

myInteger = 5;       // 5 stored in myInteger
myInteger = 8 + 3;   // 11 stored in myInteger

The right operand is an expression containing one or more operands and operators that is evaluated to determine a resulting value.  Operands within the expression can be constants, variables, properties or the results of function calls.

            myInteger = (12 + (8 * TripleThisNumber(2))) / myDog.Age;

The left side of an assignment statement can specify a variable, a property, or an indexer access.

            myDog.Age = 12;
            myArray[2] = 42;

#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.


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)


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:


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