C# Comments and Readable Code
Readable code helps the next person understand both the instructions and the reason behind them. Learn when a comment adds useful context, when a better name is enough, and how to improve a program without quietly changing its result.
What you will be able to do
- Recognize single-line and block comments and their boundaries.
- Distinguish comment markers from the same characters inside strings.
- Explain a decision or assumption without repeating obvious code.
- Improve names and layout while preserving behavior.
- Detect comments that disagree with the implementation.
- Check a readability change using predicted results and changed inputs.
Write for the next reader, including your future self
You can understand a program today because you remember why you wrote it. Another reader does not have that memory. Readable code carries enough meaning in its names, structure and explanations that someone can follow the rule without asking its author to translate every line.
A comment is source text intended for readers rather than an instruction to the running application. It can explain why a decision was made or what a small example deliberately leaves out. It cannot make an incorrect expression correct or enforce an input rule just by describing one.
Use the console programs from previous lessons as your starting point. You already know declarations, simple arithmetic and labelled output; this lesson improves how those ideas are communicated in the source. Each example is a separate complete Program.cs, and the expected output remains a reference to compare with an actual run.
Program.cs · Explain a planning decision
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Practice minutes: 40
The comment explains why five minutes are reserved. It is not a statement that prints or subtracts anything. The declarations and subtraction implement the plan. If you remove only the comment text, the result stays 40; if you remove the breakMinutes declaration too, you have changed the executable source.
A URL or quoted marker is not a source comment
The previous output lesson showed that quoted characters are data. The same rule matters here: // inside an ordinary string is part of the message, not the beginning of a comment. A URL can therefore contain slashes without hiding the rest of the call.
Before deciding that text is commented out, find the surrounding quote boundaries and any escape sequences. Syntax highlighting can help, but the actual boundaries are determined by the language. Do not repair a valid URL by deleting its slashes or adding comment markers elsewhere.
Run the next program, then change only the note text inside the second message. Its output should change. Contrast that with changing explanatory text in a real source comment, which does not itself print anything. This experiment distinguishes what the program displays from what a developer reads in the source.
Program.cs · Markers inside text stay text
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Reference: https://sovrancode.org
Markers: /* note */ and // note
The slashes in the URL and the markers in the second message belong to ordinary quoted strings. They do not begin source comments there. Read the quote boundaries before interpreting the slashes. Changing the text inside these strings changes output, even when the characters resemble a comment.
Commenting out code is a source change
Sometimes you disable one diagnostic message while investigating a program. A line comment can do that without deleting the text. Predict which calls remain active, then run the example. Restoring the disabled call changes the output because you restored an instruction, not because the comment became executable.
Keep these experiments small and reversible. If you disable a declaration while leaving later references, the source can stop compiling. If you disable a check in a larger application, the program's behavior can change. Commenting out code is not automatically a harmless readability edit.
When an experiment ends, keep the useful final version and remove distracting disabled alternatives. An existing repository's version history can preserve earlier versions. A TODO note can record a concrete remaining task, but it does not complete that task and should not be mistaken for a working feature.
Program.cs · Temporarily disable one diagnostic line
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Starting practice
Practice complete
The diagnostic call is inside a line comment and therefore does not execute. Removing the comment marker would add a third message between the existing two. This is useful during a short experiment, but do not leave a growing collection of disabled versions in the final source; version control is better suited to retaining old code.
Compilation fails: plannedMinutes has no active declaration.Commenting out the declaration removes it from the executable source while leaving a reference to its name. The compiler cannot find that name. Restore the declaration, or deliberately redesign the code that depends on it. Adding more explanation to the comment cannot provide a value to the running program.
Improve the code before explaining around it
Start with names that reveal the roles of values. plannedMinutes and completedMinutes let a reader inspect the subtraction directly. A comment explaining that a means planned minutes is a weaker solution when you are free to choose a clearer name.
Group declarations, the calculation and the output into recognizable steps. Use one statement per line, spaces around operators and consistent indentation within blocks. Blank lines can separate related work. These are readability conventions, not proof that the rule is correct; preserve string content, operators and statement order while changing layout.
Compare the compact program with the improved version. First confirm the same original output. Then change the planned and completed values in both and compare again. A single matching result is easy to obtain accidentally; changed inputs provide stronger evidence that you preserved the relationship rather than copied the answer.
Program.cs · Valid but difficult to review
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Minutes left: 25
This program is legal, but the reader has to infer what a and b mean and separate three statements packed onto one line. Before rewriting it, record that the intended calculation is planned minutes minus completed minutes. A readability edit should make that same rule easier to inspect.
Program.cs · The same rule with clearer structure
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Minutes left: 25
The names identify the roles of the values, blank lines group related steps, and the comment states an assumption instead of narrating subtraction. The output matches the compact version. That match at one input is a starting check, not a proof for every input; compare both versions again after changing the counts.
Explain decisions and limitations, not obvious syntax
A comment saying declare an integer beside an int declaration repeats what the language already shows. A note explaining that the plan reserves a break adds the reason behind a chosen value. A note explaining that this beginner report does not validate its inputs makes the example's limits clear.
Keep comments specific enough to check. This report assumes zero to total pages is more useful than this code is safe. If the requirement changes, reread the nearby comments as well as the expression. A stale explanation can mislead a reviewer precisely because it sounds confident and familiar.
Code and prose can disagree in either direction. Decide what the requirement actually is, predict the right result, and inspect the implementation. If the requirement calls for subtraction and the code adds, fix the rule. Do not simply change the comment to say addition so the disagreement disappears on paper.
Close block comments and avoid nesting them
An unfinished block comment is a compilation error, even if there is a valid output call earlier in the file. Compilation happens before this program runs. The earlier call is not executed first as a reward for appearing before the mistake.
Block comments do not nest. When the compiler encounters the first closing marker, that comment ends. An inner-looking opening marker does not make the compiler wait for an additional closing marker. This is why wrapping an existing commented region in another block can expose text you intended to hide.
Use one block with plain text inside, or use separate // lines for a longer note. After repairing the boundary, run the program and check which calls are active. A repaired delimiter can make a previously hidden call active again, so compilation success is only the first part of the check.
Program.cs · Find an unfinished block comment
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Compilation fails because the block comment never closes.An opening block marker requires a closing marker. Reaching the end of the file first is a compilation error, so even the earlier Ready call is not run. Close the note before the second call if that call is intended to execute. Do not confuse an earlier source position with a program that has already started running.
Program.cs · Block comments do not nest
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Compilation fails: the first closing marker already ended the block comment.The inner-looking opening marker does not create another nesting level. The first closing marker ends the comment, leaving the following explanatory words as invalid source. For a longer note, use one outer block with ordinary text inside, or use consecutive single-line comments. Do not wrap an arbitrary region containing block comments in another block comment.
Recognize documentation comments without overusing them
You may see triple-slash comments, written as ///, above types and members in other projects. These are XML documentation comments: tools can use their structured content to provide API documentation. They serve a different purpose from a short note beside a calculation.
You do not need to add XML documentation above every top-level statement in this lesson. Later, when you design methods and classes, descriptions of parameters, results and assumptions can help callers use those APIs. Today, focus on accurate ordinary comments and code that is readable without a large annotation layer.
Treat comments as part of the review, not a substitute for running the code. The checklist below asks whether the names are clear, the explanation adds missing context, the claim is supported and the edit preserves the behavior it promises to preserve.
A small review checklist
- Does a name already explain this?
- Prefer a useful name such as pagesRead over a vague name plus a comment saying what it stores. Rename its references consistently; changing only a comment does not rename code.
- What information would a reader otherwise miss?
- Explain a decision, an assumption, a limitation or a necessary workaround. A comment saying add two values beside an addition rarely adds anything the expression did not already say.
- Does the source actually support the claim?
- Read the code and try changed inputs. A comment saying validated, saved or secure does not implement validation, persistence or security.
- What should remain unchanged?
- For a readability-only edit, record the intended result and compare before and after. If you also fix a rule, identify that behavior change explicitly rather than presenting it as formatting.
Guided repair: when the comment and the code disagree
A report must show planned minutes minus completed minutes. Read the reassuring comment, predict the required 25, then run the original. Repair the calculation and replace the repetitive comment with an accurate limitation. Describe this as a behavior repair rather than a formatting-only change.
Program.cs · A reassuring comment can still be wrong
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Minutes left: 65
The prose says subtraction, but the executable operator is addition. The compiler accepts the arithmetic and does not test whether an English comment describes it accurately. The task's intended rule and independently predicted answer determine the repair; do not make the comment endorse an incorrect result merely to make the two agree.
Repair checkpoints
- The original source compiles and prints 65, which contradicts the required rule.
- Use subtraction so the original inputs produce 25.
- Keep the label Minutes left unchanged.
- With completedMinutes = 0, expect 45; with 45, expect 0.
- With completedMinutes = 50, expect -5 and explain that no input validation exists.
Reveal the behavior repair and explanation
Program.cs · Repair the rule and keep the assumption honest
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Minutes left: 25
Subtraction now matches the requirement, and the comment adds a real limitation rather than restating the operator. This is a behavior repair, not merely a readability edit: the original 65 changes to 25. Keep those categories separate when reviewing a change so a formatting cleanup does not hide a rule change.
Independent lab: improve readability without changing the result
Improve a working reading report without changing its behavior. The goal is for another student to understand the values, calculation and limitation without needing you to explain the source aloud.
Acceptance checklist
- Rename x to totalPages and y to pagesRead, updating every active reference.
- Put one statement per line and group inputs, calculation and output.
- Remove comments that merely restate declarations or assignments.
- Replace the unsupported safety claim with a precise assumption or limitation.
- Preserve the subtraction and the exact output label Pages left: .
- For the original 80 and 25 inputs, keep the result 55; do not hardcode it.
Program.cs · Refactor this reading report
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Pages left: 55
The arithmetic is already the rule you must preserve. The names and layout are weak, two comments merely repeat the source, and the safety claim is unsupported. Improve the names, grouping and explanation without changing the calculation or the report's exact label.
Show hints
- Write down the existing calculation before changing names.
- A name change must be applied to its references as well as its declaration.
- A useful comment can state that this version does not reject progress beyond the total.
Reveal the reference solution
Program.cs · Readable reading report
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Pages left: 55
The new names expose what the numbers mean and the comment accurately states the assumption. There is no claim that invalid progress is rejected. With the original inputs, the exact output remains Pages left: 55. Zero progress, a finished book and progress beyond the total should behave the same in both versions too.
Compare before and after
- Zero pages read: total 80 and read 0 must leave 80.
- Finished book: total 80 and read 80 must leave 0.
- Progress beyond the book: total 80 and read 90 produces -10 in both versions.
- Different book: total 120 and read 30 must leave 90.
- Read your final comment alongside the negative case. It must not claim that the program rejects it.
Frequently asked questions
Do comments print when the program runs?
Ordinary source comments do not print. A comment-looking phrase inside a string passed to WriteLine is data and can print. Distinguish the source boundary from the visible characters.
Can I put a block comment inside another block comment?
No. The first closing marker ends the comment. Use one block containing ordinary text or consecutive single-line comments instead.
Should I explain every line?
No. Prefer clear names and straightforward structure. Add context that the code alone does not provide: a decision, an assumption, a limitation or a reason for a necessary workaround.
Does a comment saying validated make the input safe?
No. A comment documents a claim; executable checks would have to implement it. In these reports, out-of-range progress still produces a negative result.
How do I know a cleanup preserved behavior?
Record the intended rule and compare before and after with the original inputs and changed values. Preserve output text and statement order deliberately. If you also repair a rule, identify that as a separate behavior change.
Can you review the source, not just its comments?
Check comment boundaries, unsupported claims, and the difference between a readability edit and a behavior repair.
Recap and next step
Use names and layout to expose the calculation. Use comments to explain a reason, assumption or limitation. Read comment boundaries carefully, keep explanations in sync with the source, and compare before-and-after behavior when improving readability.
This completes the first unit’s published lessons. Next is C# Variables and Constants, where you will follow stored values and assignments in more detail. Keep the reading report: its clear names make it a useful starting point for that work.
Official references
Original SovranCode explanations and exercises. Language rules and style guidance were checked against the references below.
Last updated: .
Know exactly where a comment starts and ends
A single-line comment starts with // outside a string and continues to the end of that physical source line. It can occupy a line of its own or follow a complete statement. A block comment starts with /* and finishes at the first following */. It can span several lines, or appear within one line.
Read the punctuation before moving code. A semicolon placed inside a single-line comment does not terminate the statement before it. If you move active code onto the end of a // line, that code becomes part of the comment. Formatting is usually about presentation, but changing these line boundaries can change what source remains active.
Use a block for a cohesive note that genuinely needs several lines. Use a short preceding line comment for a brief explanation. Neither form is a license to write a paragraph for every simple assignment. In the following report, the note explains which inputs the example assumes rather than promising that it validates those inputs.
Program.cs · State the example's assumptions
Predict the result, edit Program.cs, then run your program.
Standard input · optional
The block comment records the input assumptions and a limitation. Those words do not enforce the assumption. Set completedMinutes to 50 and the program still prints -5. A useful comment tells a reader what the example relies on without pretending the program already checks it.
Program.cs · A short note after a statement
Predict the result, edit Program.cs, then run your program.
Standard input · optional
The declaration ends at the semicolon before the comment. The rest of that source line is explanatory text. A short note can fit here; a long explanation is easier to read on its own preceding line. Keep the essential statement outside the comment rather than hoping its punctuation will be recognized inside it.