On this page
The short answerWhy C# documentation examples breakClassify blocks before choosing a checkBuild and run a file-based appPut important behavior in a test projectCheck XML documentation examples separatelyExtract Markdown fences and build themRun the checks in CITriage failures with their contextWhere DocsAlive fitsPasteable checklistThe sources we checkedFAQThe short answer
Test C# documentation examples at the level of the promise they make: build complete programs with the stated .NET SDK and package versions, put consequential behavior in a test project, and give fragments the context they need without hiding prerequisites from readers. Check XML documentation examples separately: the compiler can verify cref references, but it does not compile code inside <code>. Record skipped blocks and investigate failures before deciding whether they are documentation bugs.
Run the checks when examples or public APIs change, against release artifacts when practical, and on a schedule for dependency drift. Start with a clean environment and record the SDK, target framework, package versions and setup. The broader workflow is covered in documentation testing and SDK documentation testing.
DocsAlive recognizes csharp and cs fences but does not compile, lint or run them. It reports them as skipped, with reason not executable (csharp) and category not-executable. Use your own C# checks in CI; the service can still check supported blocks elsewhere on the same page.
Why C# documentation examples break
A C# example makes promises about more than the lines inside its fence. A reader needs an SDK, a target framework, the right assemblies and often a package. They also need to know whether the block is a complete program or a piece to place inside an existing project. A snippet can look familiar to its author while omitting context that exists only in the author's editor.
Missing using directives are a common source of confusion. A project may supply implicit imports, while a reader's project does not. A page may show a type from a package without naming its namespace, or rely on a global import defined elsewhere. The compiler error is useful evidence, but the fix depends on what the page promises: add an import to a standalone example, or explain the project context for a deliberately short fragment.
Package changes create another class of drift. A type or member may be renamed, moved or removed between releases. A README in the main branch may describe an unreleased API, while the installation command retrieves the last published package. A NuGet package ID can be wrong even when the namespace looks plausible; the package ID and the namespace are separate facts. State which package and version a reader should use, and test the installation path as well as the code.
Nullable analysis can expose assumptions that are otherwise easy to miss. A method may now return a nullable value, or an example may dereference a value without checking it. Whether a warning appears depends on project settings and the declarations involved. Treat warnings as failures in a deliberate check when the documentation promises warning-clean code, and keep those settings visible.
Async examples need a valid place for await. Top-level statements can provide that context in a complete file-based app. A fragment intended for a method must explain that it belongs in an appropriate async method. Copying only the expression into a non-async method can fail even though the operation itself is valid.
These problems appear in READMEs, SDK guides, XML doc comments and DocFX-style sites. Generated presentation does not guarantee that the source code was built. A successful site build can establish that documentation rendered; a separate check must establish that the sample compiles and behaves as described.
Classify blocks before choosing a check
A useful inventory says what the reader is meant to copy, what context exists, and what result the page promises. Use that inventory to choose a check rather than treating every fence as an independent application.
| Block | Reader’s intended use | Check |
|---|---|---|
| Complete program | Save or copy the whole example and run it | Build, then run and verify its meaningful result |
| Fragment | Insert code into a documented file, method or sequence | Mark it as a fragment; compile it in a representative wrapper or test project |
| Project or configuration file | Save settings in a named file | Validate in a representative project and confirm the documented settings have the intended effect |
| Output | Compare the program’s result with the page | Compare stable values, accounting for explicitly variable fields |
A complete program can use top-level statements or a declared entry point. A fragment may show one method call, a type member or a continuation of an earlier block. Neither needs to be longer than necessary, but the page should say which it is. A code block that is intended to stand alone should not depend on an undocumented class, variable or package.
Keep a page’s sequence in view. A later example might depend on a file or value created earlier, while two tabs might be alternatives. An isolated compilation check is valuable for standalone files, but it does not prove that a multi-step tutorial works in order. For a sequence, reproduce the documented setup and run the path as a reader would. Quickstart testing covers that broader path.
Build and run a file-based app
The .NET 10 SDK and later support file-based apps. The SDK supplies a virtual project for a C# source file, so a small standalone example does not need a checked-in project file. Put directives at the top of the file. The following complete example uses the base class library and explicitly targets .NET 10:
#:property TargetFramework=net10.0
using System;
Console.WriteLine("Documentation example works.");
Save it as Example.cs. With the .NET 10 SDK installed, run:
dotnet run --file Example.cs
The shorthand also runs a file-based app:
dotnet Example.cs
There is a distinction when a .csproj exists in the current directory. dotnet run Example.cs without --file can run the project and pass Example.cs as an argument instead of treating it as the source file. Use dotnet run --file Example.cs in repository instructions to make the intended behavior explicit. The file-based app documentation describes these forms and the generated project.
Build the file without running its program:
dotnet build Example.cs
A build proves that the source compiled under that SDK and its resolved dependencies. It does not prove that the program reaches the result shown in the docs. Run complete examples as well, and compare the stable output or observable result with the page. A build also performs restore as needed, so a dependency or network failure deserves its own diagnosis.
Make warnings visible
For examples expected to compile without warnings, promote warnings to errors:
dotnet build Example.cs -p:TreatWarningsAsErrors=true
The TreatWarningsAsErrors property turns compiler warnings, such as a possible null dereference, into build errors. The same setting can live in the file itself as #:property TreatWarningsAsErrors=true. Do not use the -warnaserror switch here: in our run with the .NET 10.0.404 SDK, dotnet build Example.cs -warnaserror stopped treating the file as a file-based app and failed with error MSB4025. A warning failure can reveal a real issue, such as unsafe nullable usage or a deprecated API, but it can also come from a dependency or a changed SDK. Inspect the warning and its source before changing the example. The compiler warning options explain more selective settings.
Keep the policy consistent with the documentation. If readers are expected to use nullable analysis, compile the mirrored example with that analysis enabled and address relevant warnings. If the page shows a warning intentionally, label its purpose and test it separately rather than silently excluding it.
State package dependencies
For a file-based app that uses a real NuGet package, put a #:package directive before the code and specify the version being tested. The following is an illustrative directive, not a runnable package example: Acme SDK, its Acme.Sdk namespace and the NuGet ID Acme.Sdk are fictional.
#:package Acme.Sdk@1.2.3
Replace the fictional ID and version with the package that actually supplies the documented API. File-based apps support special version choices, but an explicit version makes the tested dependency clear. A directive without a version is not a general substitute: it requires central package management unless a version such as @* is supplied. A floating version can be useful for a separate drift check, but it gives a different result from a reproducible pinned check.
Confirm the package ID in the install instruction, the namespace in the source and the API in the installed version. If a page covers several package versions, identify which examples apply to each. Test the minimum supported combination and a current supported combination where those are distinct promises.
Check a small fragment quickly
For a quick experiment, pipe a complete top-level statement to the SDK:
printf '%s\n' 'System.Console.WriteLine("Hello from a fragment.");' | dotnet run -
This checks that statement in the context supplied by a file-based app. It does not prove that the same line works at every insertion point in a reader’s project. It also does not test an accompanying package instruction or the surrounding tutorial.
For a fragment that depends on a variable, make the wrapper explicit. The marker below tells the extraction script later in this guide that the block is a fragment; it is nevertheless valid in the wrapper shown:
// fragment
using System;
string name = "reader";
Console.WriteLine($"Hello, {name}.");
In a real fragment, keep the original lines identifiable and add only the setup needed to represent the page. If a wrapper must invent a value the page never supplies, investigate whether the documentation is missing a step. A test harness can supply a fixture, but the test record should say that it did.
Put important behavior in a test project
Compilation catches syntax, names, types and some warnings. It cannot establish that an example returns the correct value, handles an error as promised or produces the documented output. Mirror important examples into a test project, run it with dotnet test, and assert the outcomes that matter to readers.
A test project is especially useful for SDK examples that exercise a released package, examples with several related calls, and code that must work under more than one target framework. Keep the source example and its tested counterpart close enough that reviewers can see when one changes without the other. A link or comment identifying the source page and section is often sufficient.
Choose the dependency under test deliberately. A project reference to the current checkout answers whether the example works with that checkout. A reference to the built release artifact checks packaging as well. A check against the published package verifies the installation path available to readers after publication. Record which one ran; a passing checkout test alone does not prove that a published package contains the same API.
Use stable assertions. If output contains a generated identifier or a time, verify the meaningful structure or behavior rather than hard-coding an incidental value. If the docs show an exact result for fixed input, check that exact result. Avoid a test setup that supplies undocumented imports, configuration or initialization without recording it.
The dotnet test documentation describes how the command builds and runs a test project or solution. Your repository’s test project determines its own dependencies and runner configuration.
Check XML documentation examples separately
XML documentation comments can include <example> and <code> elements. The compiler checks whether a cref reference points to an existing target and can warn when it does not. It does not compile the C# text inside <code>. A clean documentation build therefore does not establish that the example’s imports, member names or behavior remain valid. See the recommended XML documentation tags.
Extract those examples into compiled files, or mirror them into a test project. Preserve the intended context: an example that demonstrates an instance member may need an instance and setup that the comment describes nearby. When mirroring, give the test a traceable reference back to the documented member and review both copies together.
For generated API reference pages, test the source comments and inspect the generated page. The first check addresses code validity; the second catches presentation problems such as lost indentation or unclear context. API reference documentation testing describes checks beyond code execution.
Extract Markdown fences and build them
The following Python 3 script extracts simple, unindented Markdown fences labeled csharp or cs. It writes one .cs file per block into a temporary directory and builds each block except those containing a // fragment marker. It reports the source file and line, prints a summary and exits non-zero if a build fails or a matching fence is unclosed.
Save it as check_csharp_docs.py, then pass one or more Markdown files. It requires Python 3.12 and the .NET 10 SDK. Run it only on documentation whose code and package directives you trust: building can restore dependencies and invoke build tooling.
import re
import subprocess
import sys
import tempfile
from pathlib import Path
OPEN = re.compile(r"^(`{3,}|~{3,})\s*(csharp|cs)\s*$", re.I)
FRAGMENT = re.compile(r"^\s*//\s*fragment\b", re.I)
def blocks(path):
lines = path.read_text(encoding="utf-8").splitlines(keepends=True)
i = 0
while i < len(lines):
match = OPEN.match(lines[i].rstrip("\r\n"))
if not match:
i += 1
continue
fence = match.group(1)
start = i + 1
i += 1
body = []
while i < len(lines):
line = lines[i].rstrip("\r\n")
if re.fullmatch(re.escape(fence[0]) + r"{" + str(len(fence)) + r",}\s*", line):
yield start, "".join(body)
i += 1
break
body.append(lines[i])
i += 1
else:
raise ValueError(f"{path}:{start}: unclosed fence")
def main():
if len(sys.argv) < 2:
print("Usage: python check_csharp_docs.py FILE.md [FILE.md ...]")
return 2
built = skipped = failed = 0
with tempfile.TemporaryDirectory(prefix="csharp-docs-") as temp:
root = Path(temp)
number = 0
for argument in sys.argv[1:]:
path = Path(argument)
try:
for line, code in blocks(path):
number += 1
label = f"{path}:{line}"
if any(FRAGMENT.match(part) for part in code.splitlines()):
skipped += 1
print(f"SKIP {label}: fragment")
continue
sample = root / f"Example{number}.cs"
sample.write_text(code, encoding="utf-8")
result = subprocess.run(
["dotnet", "build", str(sample), "-p:TreatWarningsAsErrors=true"],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
check=False,
)
if result.returncode:
failed += 1
print(f"FAIL {label}\n{result.stdout}")
else:
built += 1
print(f"PASS {label}")
except (OSError, ValueError) as error:
failed += 1
print(f"FAIL {error}")
print(f"Summary: {built} built, {skipped} skipped, {failed} failed")
return 1 if failed else 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except FileNotFoundError as error:
print(f"Required tool not found: {error}")
raise SystemExit(1)
For example, run it from the repository root:
python3 check_csharp_docs.py README.md docs/guide-1.md
This is a starting point, not a complete Markdown parser. It handles unindented fences with a language label alone; it does not handle nested lists, additional fence attributes, MDX or XML comments. It does not run the compiled programs or compare output. It treats every unmarked matching block as a standalone file, so mark intentional fragments and give them separate coverage. Adapt discovery and parsing to the actual documentation format before relying on the count.
A successful run with zero extracted blocks is also possible. Review the summary and the list of input files; in a production check, enforce an expected inventory or minimum coverage appropriate to the repository. Do not let an empty scan stand in for evidence that examples passed.
Run the checks in CI
This GitHub Actions outline checks two named Markdown files on pushes and pull requests. Commit the script above and adjust the paths to match the repository. The runner must have Python available, and the C# examples selected by the script must be suitable for independent builds.
name: Check C# documentation
on:
push:
pull_request:
jobs:
csharp-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-dotnet@v6
with:
dotnet-version: '10.0.x'
- name: Build Markdown examples
run: python3 check_csharp_docs.py README.md docs/guide-1.md
- name: Run the test project
run: dotnet test tests/DocumentationTests
Replace tests/DocumentationTests with the actual test project path. This outline assumes that project exists; create and maintain it before enabling the last step. The setup action documentation covers the SDK input.
Pinning the SDK line to 10.0.x keeps this job on that feature line while allowing servicing updates. Record the SDK selected in the job log. If the product supports several SDK or target framework combinations, add separate explicit jobs for the combinations you promise. A scheduled job can check dependency drift; a release job should identify whether it uses the checkout, release artifact or published package. See the GitHub Actions documentation testing guide for workflow design.
Record support and prerequisites
As read on November 10, 2026, .NET’s support policy lists .NET 10 as LTS through November 14, 2028. .NET 8 and .NET 9 reached end of support on November 10, 2026, and .NET 11 STS was released that day.
Support status and compatibility are different facts. A program may still compile on an unsupported release, while a supported runtime does not guarantee that a particular package or sample supports it. State the minimum SDK, target framework and tested package version on the page. In particular, the file-based workflow in this guide requires the .NET 10 SDK or later. Revisit the policy and test environment as releases change.
Triage failures with their context
A failure is a signal to investigate, not a complete diagnosis. Keep the command, source location, SDK, target framework, package version and full error available to the reviewer.
| Finding | Likely interpretation | Next action |
|---|---|---|
| Missing type or member in the stated package version | Possible API drift or missing import | Reproduce with the documented package; correct the API or prerequisite |
| NuGet restore cannot find the stated ID or version | Possible installation documentation bug | Verify the ID, version and configured feed |
| Unmarked fragment lacks a class or context | Classification or documentation gap | Mark it as a fragment and compile it in a representative wrapper |
| Nullable or deprecation warning fails the build | Code or policy needs review | Identify the warning source and decide whether the sample should change |
await is outside a valid context |
Example or wrapper lacks required context | Show a complete async context or explain the insertion point |
| Network or feed unavailable | Environment may have prevented restore | Retry or inspect the service before attributing it to the docs |
| Output differs | Possible stale output or variable data | Compare the promised stable values and document legitimate variation |
An example that needs a credential, external service or fixture needs a separate plan. Use an authorized test environment where appropriate, keep secrets out of the page and logs, and state what a check could not cover. A passing compile is still useful evidence, but it is not evidence that an external request succeeded. See credentials in documentation examples.
Where DocsAlive fits
Label C# fences csharp or cs so a scan reports them explicitly. Both labels map to C#, and those blocks are skipped with reason not executable (csharp) and report category not-executable. They have no C# pass or fail result from the service. Your own SDK build, execution and test-project checks remain necessary.
The service can check supported blocks on the same page, including shell commands, HTTP requests, JSON or TOML, Python and JavaScript. It processes a page in order in a fresh container for that page, and reports findings with their context. The default runner has no .NET SDK; a shell block invoking dotnet there would likely be reported as a missing tool. Credential-gated blocks are classified rather than run with real keys. See supported frameworks and languages and finding categories.
Use both reports to understand coverage. A skipped C# block makes the gap visible; it does not establish that the sample compiled. Likewise, a supported block’s result should be interpreted according to the check that actually ran. A maintainer still needs to review prose, prerequisites and whether the page gives readers a coherent path.
Pasteable checklist
- [ ] Inventory C# examples in READMEs, guides, API comments and generated sites.
- [ ] Label fences
csharporcsand distinguish complete files from fragments. - [ ] State the minimum SDK, target framework, package ID and tested version.
- [ ] Check imports, nullable settings and valid async context.
- [ ] Build standalone files with the stated SDK and a deliberate warning policy.
- [ ] Run complete examples and compare their stable results with the page.
- [ ] Compile fragments in representative wrappers without hiding missing prerequisites.
- [ ] Mirror important behavior and XML comment examples into a test project.
- [ ] Test release artifacts or published packages when those are the reader’s install path.
- [ ] Record skipped, credential-dependent and externally blocked checks.
- [ ] Run checks on relevant changes and releases, and schedule drift checks.
- [ ] Review failure causes before filing or blocking on a documentation bug.
The sources we checked
These sources were read on November 10, 2026.
| Source | What it covers |
|---|---|
| File-based apps | .NET 10 file-based execution, directives, stdin and project-directory behavior |
dotnet build |
Building with the SDK and MSBuild switches |
| Compiler warning options | Warning treatment and warning-as-error settings |
dotnet test |
Building and running tests |
| Recommended XML documentation tags | Example and code tags and cref checking |
| .NET support policy | Release support status and dates |
| Setup .NET action | SDK selection in GitHub Actions |
FAQ
Can a C# documentation example run without a project file?
Yes. The .NET 10 SDK and later support file-based apps. Save a complete example as a C# file and use dotnet run --file with its path. State the minimum SDK and any package requirements on the page.
Does a successful build prove an example is correct?
No. A build checks compilation under the selected settings and dependencies. Run complete examples and verify their meaningful results; use a test project for behavior that deserves assertions.
Why use --file in a repository?
When a project file exists in the current directory, dotnet run followed by a C# filename without --file can run the project and pass that filename as an argument. The explicit option selects the file-based app.
Does the compiler test code in XML documentation comments?
The compiler checks cref references, but it does not compile the example text inside a code element. Extract or mirror those examples into compiled files and tests.
Should every fragment build by itself?
No. Identify fragments and compile them in representative context. Explain the insertion point and prerequisites to readers, and record any setup supplied by the test harness.
Can DocsAlive run C# examples?
It recognizes csharp and cs fences but skips them as not executable, with category not-executable. Use your own C# checks in CI; supported blocks elsewhere on the page can still be checked.




