Prompting AI assistants for code: goal, context, constraints and examples, instruction files, asking for edge cases and tests first, decomposing work, and iterating on concrete failures.
A good code prompt reads like a good ticket for a capable contractor who has never seen the repo:
Result<T> type in Shared/Result.cs").Then ask for edge cases and tests first, review them, and only then ask for the implementation. When it's wrong, paste the actual compiler error or failing test instead of "try again". Rules you repeat go in an instructions file. The trade-off: a longer prompt costs a minute, a vague one costs a review cycle.
"I treat a prompt like a ticket for a smart contractor who has never seen our codebase. The model only knows what's in its context window, so I give it four things: the goal, the context, the constraints and an example. The goal is the outcome, not the steps. The context is the actual files: I reference the interface, the entity, the existing handler next to it, and I say '.NET 10, C# 14, EF Core 10' so it doesn't drift back to .NET 6 patterns. Constraints are where most of the value is: 'use FluentValidation, return
Result<T>, don't change the public contract, don't add packages'. And one existing class in house style beats a paragraph describing it.For anything with logic I flip the order: I ask it to list edge cases and write failing tests first, I check those against the requirement, then I ask for the implementation that makes them pass. That catches misunderstandings while they're cheap. I also decompose: 'add the endpoint', then 'add validation', then 'add the migration', each one reviewable, rather than one giant request that produces a 600-line diff.
The mistake I see is iterating by vibes: 'that's wrong, try again'. The model has no new information, so it guesses differently. I paste the exact compiler error or the failing assertion, or I say precisely which line is wrong and why. If the conversation has gone off the rails I start fresh, because a polluted context keeps steering it back to the wrong idea. And anything I type more than twice goes into
copilot-instructions.mdorAGENTS.mdso the whole team benefits. Good prompting is mostly good specification."
| Part | What to give | .NET example |
|---|---|---|
| Goal | The outcome and done criteria | "Add POST /api/orders/{id}/cancel; returns 204, or 409 if already shipped" |
| Context | Files, types, versions | #file:Orders/Order.cs, #file:Orders/ShipOrderHandler.cs, .NET 10 |
| Constraints | Libraries, patterns, limits | "MediatR handler, FluentValidation, no new packages, don't touch Program.cs" |
| Example | One existing class in house style | "Follow ShipOrderHandler exactly" |
| Output format | What you want back | "Only the changed files, then a list of assumptions" |
| Bad follow-up | Better follow-up |
|---|---|
| "That doesn't work, try again" | "CS1061 on line 14: Order has no MarkCancelled method. Use Order.Cancel(TimeProvider) from Order.cs" |
| "Make it better" | "Extract the status check into Order.Cancel() so the rule lives in the entity" |
| "Add tests" | "Add xUnit tests for: already cancelled, already shipped, not found, concurrent cancel" |
| Situation | Technique |
|---|---|
| Logic with edge cases | Tests first, then implementation |
| Change across 3+ files | Ask for a plan, edit it, execute step by step |
| Same correction for the third time | Move the rule into the instructions file |
| Assistant keeps returning to a rejected idea | New conversation with a corrected prompt |
On [our team] we added a [40-line] AGENTS.md with our conventions and three prompt files for common tasks (new endpoint, new migration, new test class). Review comments on AI-assisted PRs about style and structure dropped from roughly [6 to 2] per PR within [a month], because the rules were in context instead of in reviewers' heads.
Checks whether the candidate can steer an assistant deliberately and verify its output, rather than accept whatever it produces.
Green flags
Red flags
The model continues text. A vague prompt leaves many plausible continuations, and the most common one in the training data tends to win, which is often old or generic. Each constraint removes wrong continuations. Concrete references (file names, type names, versions) also help the tool retrieve the right code into context.
vague prompt ──► many plausible answers ──► most common pattern (often outdated)
specific prompt ──► few plausible answers ──► the one that fits your repo
The internet holds far more .NET Framework and .NET Core 3.1–6 code than .NET 10 code, so without a version the model drifts to the majority. Saying ".NET 10, C# 14" (or putting it in the instructions file, and keeping <TargetFramework>net10.0</TargetFramework> in an open .csproj) shifts it towards:
| Without a version you often get | With ".NET 10, C# 14" you should get |
|---|---|
Startup.cs with ConfigureServices |
Minimal hosting in Program.cs |
Newtonsoft.Json attributes |
System.Text.Json, source-generated contexts |
| Controllers for a two-line endpoint | Minimal APIs with TypedResults |
DateTime.UtcNow in logic |
TimeProvider (and FakeTimeProvider in tests) |
| Constructor + private readonly fields | Primary constructors, collection expressions |
ISystemClock, IHostingEnvironment |
Their replacements (TimeProvider, IWebHostEnvironment) |
Even then, verify unfamiliar members in the official docs: the version hint narrows the guess, it doesn't make it a lookup.
org / repo instructions (always on: copilot-instructions.md, AGENTS.md)
prompt files / templates (reusable: new-endpoint.prompt.md)
conversation (this task: goal, constraints, examples)
referenced files (#file, selection, terminal output)
Put stable rules in the top layers so each prompt can be short and so the whole team gets the same standard. Keep instruction files short and specific: long ones get diluted and cost tokens on every request. Review them in PRs like code, because they shape every AI-assisted change.
Asking for edge cases first exposes the model's understanding before code exists and gives you an executable definition of done. For a typical Web API + EF Core slice, a good edge-case list looks like this, and you check it against the requirement before any implementation:
| Area | Edge cases to demand |
|---|---|
| Input | Empty / whitespace strings, max length, negative or zero quantities, unknown enum values |
| State | Not found (404), wrong state (409), already done (idempotent 204) |
| Concurrency | Two cancels at once: DbUpdateConcurrencyException with a rowversion token, second gets 409 |
| Time | Inclusive vs exclusive end dates, time zones (TimeProvider with FakeTimeProvider) |
| Security | Another user's order (403/404), missing scope |
| Data | Paging boundaries, empty result, very large page size capped |
Agent mode can then loop on dotnet test until green, and you review short tests instead of reasoning through the whole implementation. Tests must come from the requirement, otherwise they only encode the model's guess.
Large requests fail in compounding ways: one wrong assumption early spreads through every file. Small steps keep each diff reviewable and let you correct course. A useful pattern is plan, then execute: ask for a numbered plan, edit the plan, then ask it to do step 1.
Everything earlier in the conversation stays in context. A rejected approach still influences the next answer. Starting a new chat with a clean, corrected prompt is often faster than arguing.
Ask for "assumptions you made" and "anything you're unsure about". Models will often surface a guessed API or an ambiguous requirement when invited to. It doesn't replace verification, but it tells you where to look first.
Generated code still goes through the same gates as human code: analysers and .editorconfig (TreatWarningsAsErrors, nullable), formatting (dotnet format), architecture tests (NetArchTest) and human review. Those gates are what keep AI output consistent with the rest of the codebase over time.
new-endpoint.prompt.md for your repo and use it for the next endpoint.A reusable prompt file, and the test-first output we review before any implementation exists.
<!-- .github/prompts/new-endpoint.prompt.md -->
Goal: add the endpoint described below to the Orders API.
Context: .NET 10, C# 14, minimal APIs, MediatR, FluentValidation, EF Core 10.
Follow exactly: Orders/ShipOrder/* (command, handler, validator, endpoint, tests).
Constraints:
- Do not change public contracts or Program.cs. No new NuGet packages.
- Return TypedResults; map domain errors to ProblemDetails (409 for state conflicts).
- Every async method takes a CancellationToken.
Steps:
1. List edge cases and write failing xUnit tests. Stop and wait.
2. Implement until the tests pass.
Output: changed files only, then a list of assumptions.
namespace Orders.Tests.CancelOrder;
// Step 1 output: tests derived from the requirement, reviewed before implementation.
public sealed class CancelOrderHandlerTests(OrdersDbFixture db) : IClassFixture<OrdersDbFixture>
{
[Fact]
public async Task Shipped_order_cannot_be_cancelled()
{
var order = await db.SeedAsync(OrderStatus.Shipped);
var handler = new CancelOrderHandler(db.Context, TimeProvider.System);
var result = await handler.Handle(new CancelOrder(order.Id), CancellationToken.None);
result.Error.Should().Be(OrderErrors.AlreadyShipped); // endpoint maps this to 409
}
[Fact]
public async Task Cancelling_twice_is_idempotent()
{
var order = await db.SeedAsync(OrderStatus.Cancelled);
var handler = new CancelOrderHandler(db.Context, TimeProvider.System);
var result = await handler.Handle(new CancelOrder(order.Id), CancellationToken.None);
result.IsSuccess.Should().BeTrue(); // no error, and no second audit row
}
}
Startup.cs, Newtonsoft.Json or old EF Core idioms. Instead: say ".NET 10, C# 14, EF Core 10" or put it in the instructions file.ISystemClock was replaced by TimeProvider) and the model may still mix versions. Instead: check unfamiliar members against the .NET 10 docs and let the compiler and analysers have the last word.Prompting is specification under another name. Engineers who write clear tickets and clear tests get good results; the same skills transfer. The senior move is to make the good prompt the team default: instruction files and prompt templates in the repo, reviewed like code, so quality doesn't depend on who typed the request.
| Technique | When it fits | Cost | When not to |
|---|---|---|---|
| Five-part prompt | Any non-trivial generation | A minute of writing | One-line completions |
| Tests first | Logic with edge cases | Extra round trip | Pure boilerplate |
| Plan then execute | Multi-file changes | Reviewing a plan | Single-function edits |
| Instruction / prompt files | Rules repeated across the team | Maintenance like any doc | Personal one-off preferences |
| Fresh conversation | Context polluted by wrong turns | Re-stating context | Early in a productive thread |
Measure it by review rework on AI-assisted PRs: if reviewers keep leaving the same comment, that rule belongs in the instructions file.
An AI coding assistant is a large language model that predicts the next token given a context window the IDE assembles for it: the current file around the cursor, other open tabs, repository instructions such as .github/copilot-instructions.md or AGENTS.md, and snippets retrieved from the codebase. It has no compiler inside it, so it produces plausible code, not checked code.
dotnet build and dotnet test, reads the errors and iterates, or works from an issue and opens a PR.It is excellent at boilerplate, tests and explaining code, and weak at novel design and anything newer than its training data. The trade-off: speed of first draft against the cost of verifying it.
AI is a strong first pass, never the final check.
The trade-off: minutes saved on drafting against the risk of false confidence, so verification is part of the workflow.
Last updated 23 Nov 2026.