Comments in Code
As you read the code examples, you often encounter the comment symbol ('). This symbol tells the Visual Basic compiler to ignore the text following it, or the comment. Comments are brief explanatory notes added to code for the benefit of those reading it.
It is good programming practice to begin all procedures and functions with a brief comment describing the functional characteristics of the procedure (what it does), for your own benefit and the benefit of anyone else who examines the code. You should separate the implementation details (how the procedure does it) from comments that describe the functional characteristics. When you include implementation details in the description, remember to update them when you update the function.
Comments can follow a statement on the same line, or occupy an entire line. Both are illustrated in the following code:
' This is a comment beginning at the left edge of the screen. Text1.Text = "Hi!" ' This is an inline comment.
If your comment requires more than one line, use the comment symbol on each line:
' The text of this comment is too long to fit on a single line, so we ' break it into two lines. Some comments might need three or more lines.
The following chart provides general guidelines for what types of comments should be listed in a particular section of code. These are suggestions; Visual Basic does not enforce "rules" for adding comments. Write what works best, both for you and for anyone else who reads your code:
|Section heading||Comment description|
|Purpose||Describes what the procedure does (not how it does it)|
|Assumptions||Lists each external variable, control, open file, or other element accessed by the procedure|
|Effects||Lists each affected external variable, control, or file, and the effect it has (only if it is not obvious)|
|Inputs||Specifies the purpose of the argument|
|Returns||Explains the values returned by functions|
Remember the following points:
- Every important variable declaration should include an inline comment describing the use of the variable being declared.
- Variables, controls, and procedures should be named clearly enough that inline commenting is needed only for complex implementation details.
- Comments cannot follow a line-continuation sequence on the same line.
You can add or remove comment symbols for a block of code by selecting two or more lines of code and choosing the Comment and Uncomment buttons on the Edit toolbar.
Note You can also add comments to your code by preceding the text with the REM keyword. However, the ' symbol and the Comment/Uncomment buttons are easier to use and require less space and memory.