📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you prompt an AI coding assistant well for code? What context, constraints and examples do you give it, how do you ask for tests and edge cases, and how do you iterate when the first answer is wrong?

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.

Intermediate Theory Intermediate ai ai-assisted-development github-copilot prompt-engineering testing

🎯 Key points

  • Structure: goal, context, constraints, example, output format
  • Reference the real files, interfaces and the target framework (.NET 10, C# 14)
  • State what must not change: public contracts, other files, dependencies
  • Ask for edge cases and failing tests before the implementation
  • Decompose large tasks into small, verifiable steps
  • Iterate with the actual compiler error or failing test, not 'try again'
  • Put repeated rules in copilot-instructions.md / AGENTS.md / prompt files
  • Start a fresh conversation when context is polluted

⏱ 30-second answer

A good code prompt reads like a good ticket for a capable contractor who has never seen the repo:

  • Goal: what should be true when done.
  • Context: the files, interfaces and target framework ("ASP.NET Core 10, EF Core 10, our Result<T> type in Shared/Result.cs").
  • Constraints: libraries to use, patterns to follow, what must not change.
  • Example: an existing class in house style.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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.md or AGENTS.md so the whole team benefits. Good prompting is mostly good specification."


The prompt structure

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"

Iterating well

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"

When to use which technique

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can steer an assistant deliberately and verify its output, rather than accept whatever it produces.

Green flags

  • Gives a clear structure: goal, context, constraints, example
  • Names the framework version and real files
  • Asks for edge cases and tests before implementation
  • Iterates with concrete errors; knows when to start fresh
  • Shares rules through instruction or prompt files

Red flags

  • "I just ask it and fix what's wrong"
  • Lets it write both code and tests, then trusts green
  • Huge single prompts producing huge diffs
  • No notion of what context the model sees

📚 Learn in depth

1. Why structure matters

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

2. Why the version number changes the output

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.

3. Layers of context

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.

4. Tests first, concretely

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.

5. Decomposition

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.

6. Context pollution

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.

7. Asking it to show uncertainty

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.

8. Fitting the output into the codebase

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.

Try it yourself

  1. Ask for the same feature with a one-line prompt and with the five-part structure; diff the results.
  2. Ask for a minimal API endpoint without a version, then with ".NET 10, C# 14"; list the differences.
  3. Write a new-endpoint.prompt.md for your repo and use it for the next endpoint.
  4. Ask for edge cases only for a date-range filter; count how many you would have missed.
  5. Feed a real compiler error back verbatim vs "try again" and compare how often each fixes it.

💻 Code

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
    }
}

⚠ Common mistakes

  • Mistake: One-line prompts like "write an orders API". Why it is wrong: the model fills gaps with the most common, often outdated pattern. Instead: give goal, context, constraints and an example.
  • Mistake: Not stating the framework version. Why it is wrong: you get 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.
  • Mistake: Trusting that a version hint makes the answer current. Why it is wrong: APIs change between releases (for example 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.
  • Mistake: Asking for implementation and tests together. Why it is wrong: the tests mirror the implementation's assumptions. Instead: ask for edge cases and tests first, check them, then implement.
  • Mistake: "Try again" after a wrong answer. Why it is wrong: no new information, just a different guess. Instead: paste the exact error, failing test or the line that's wrong and why.
  • Mistake: One huge request for a whole feature. Why it is wrong: early wrong assumptions spread and the diff is unreviewable. Instead: plan first, then small steps.
  • Mistake: Continuing a long, confused conversation. Why it is wrong: rejected ideas stay in context and keep returning. Instead: start fresh with a corrected prompt.
  • Mistake: Writing giant instruction files. Why it is wrong: rules get diluted and every request pays for the tokens. Instead: keep them short, specific and versioned with the code.
  • Mistake: Pasting production data or secrets as "context". Why it is wrong: the prompt leaves your machine. Instead: use synthetic examples and follow the data policy.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about context without explaining where it comes from Why: Checks the mental model behind the prompting habits
    How to answer

    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.

    • Inline completion: fast fill-in-the-middle suggestions as you type.
    • Chat: ask, explain, generate or edit with a conversation.
    • Agent mode / coding agent: plans, edits many files, runs 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.

  2. When: Candidate mentions asking the assistant for tests Why: Checks how they verify AI-generated tests and reviews
    How to answer

    AI is a strong first pass, never the final check.

    • Code review: tools like Copilot code review catch missing null checks, undisposed resources, inconsistent naming and obvious logic slips in seconds, so humans can focus on design and domain rules. It comments; a human still approves.
    • Tests: great for scaffolding and edge-case lists, risky as proof: generated tests often assert what the code does, not what it should do. Check them by breaking the code or with mutation testing (Stryker.NET).
    • Docs: fast drafts of XML comments, READMEs and ADR skeletons; every statement is checked against the code.

    The trade-off: minutes saved on drafting against the risk of false confidence, so verification is part of the workflow.

↩ Usually asked after

More in AI-Assisted Development

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me