Sams Teach Yourself C# in 24 Hours

Sams Teach Yourself C# in 24 Hours

By James Foxall and Wendy Haro-Chun

Adding Comments to Your Code

One of the simplest things you can do to reduce bugs from the start—and make tracking down existing bugs easier—is to add comments to your code. A code comment is simply a line of text that C# knows isn't actual code. Comment lines are stripped from the code when the project is compiled to create a distributable component, so comments don't affect performance. C#'s code window shows comments as green text. This makes it easier to read and understand procedures. You should consider adding comments to the top of each procedure stating the purpose of the procedure. In addition, you should add liberal comments throughout all procedures, detailing what's occurring in the code.

To create a comment, precede the comment text with two forward slash marks (//). For example, a simple comment might look like this:

// This is a comment because it is preceded with double forward slashes.

Comments can also be placed at the end of a line of code, like this:

int intAge;        // Used to store the user's age in years.

Everything to the right of and including the double forward slashes in this statement is a comment. C# also supports a second type of comment. This allows for comments to span multiple lines without forcing the developer to add // characters to each line. The comment begins with an open comment mark of a forward slash, followed by an asterisk (/*), and the comment closes with a close mark of an asterisk followed by a forward slash (*/). For example, a comment can look like this:

/*     Chapter 16 in Sams TY C#
focuses on debugging code, a topic
every developer spends a lot of time on.  */

By adding comments to your code, you don't have to rely on memory to decipher the code's purpose or mechanics. If you've ever had to go back and work with code you haven't looked at in a while, or had to work with someone else's code, you probably already have a great appreciation for comments.

Double-click the button now to access its Click event and add the following two lines of code (comments, actually):

// This procedure divides 100 by the value entered in
// the text box txtInput.

Notice that after you enter the second forward slash, both slashes turn green. Comments, whether single line (//) or multiline (/* comments */), will be displayed in a green font in Visual Studio.

When creating code comments, strive to do the following:

Share ThisShare This

Informit Network