The best C# prompts tell the model your target framework, C# version and app type (ASP.NET Core, library, desktop or worker), paste the real code and the compiler or runtime output, and ask for one specific change. Below are 13 C# prompts for ChatGPT, Claude, Claude Code and Codex covering modern C#, nullable reference types, async code, ASP.NET Core, EF Core, tests and upgrades.
For general jobs such as explaining code or writing a regex, see the coding prompts. For writing the SQL behind your queries, see the SQL prompts. The prompts here are specific to C# and .NET.
How to use these prompts
Copy a prompt, replace each blank in double braces, or keep the default after the colon. {{target_framework:net10.0}} means the model should assume .NET 10 unless you change it.
Three habits make the answers better:
- State the target framework. Microsoft's support policy page lists .NET 10 as the current LTS release, supported until 14 November 2028, and shows .NET 8 and .NET 9 both reaching end of support on 10 November 2026. The C# version follows the framework: C# 14 ships with .NET 10.
- Paste compiler warnings with their codes. Nullable warnings and analyzer messages include an ID and a line number the model can work from.
- Name your stack. Say which test framework, data access library and logging setup you use, or the model may pick different ones.
In an agent, let it run dotnet build and dotnet test itself and report the output.
How do you write modern C# with AI?
1. Review code for modern C# idioms
For older C# or code written in a hurry.
Review this C# code for modern, idiomatic style. Target framework: {{target_framework:net10.0}}, C# {{csharp_version:14}}.
Check: nullable annotations, records for immutable data, pattern matching and switch expressions instead of if/else chains, primary constructors where they reduce boilerplate, collection expressions, using declarations for IDisposable, async all the way down, and LINQ only where it stays readable.
For each issue, show before and after with one sentence on why. Do not change public API signatures unless I agree, and do not use language features newer than my C# version.
{{code}}
2. Adopt C# 14 features where they help
For a codebase that just moved to .NET 10. Microsoft lists C# 14 features including extension members, the field keyword for property accessors and null-conditional assignment.
This project just moved to .NET 10 and C# 14. Find places in this code where C# 14 features make it clearer:
{{code}}
Consider: field-backed properties instead of explicit backing fields, null-conditional assignment (x?.Prop = value) instead of null checks before assignment, and extension members where we have static helper classes.
For each suggestion, show before and after and explain the benefit. Flag any spot where a member or local named field would conflict with the new field keyword. Skip changes that only save a line.
3. Enable nullable reference types in an existing project
For a project that predates nullable reference types. Microsoft's nullable migration strategies describe four defaults (disable, enable, warnings, annotations) and recommend starting with the deepest leaf types and working outward.
Help me turn on nullable reference types in this project.
Project facts: {{facts:about 200 files, actively developed, one public NuGet package}}.
1. Recommend a default Nullable setting (disable, enable, warnings or annotations) for the migration and explain why for this project.
2. Give the file order, starting with leaf types that have the fewest dependencies.
3. For this file, add annotations and fix the warnings without using the ! operator or null! unless you explain why the value can never be null:
{{code}}
How do you get async C# right?
4. Fix sync-over-async and blocking calls
For hangs, deadlocks or slow responses under load. The ASP.NET Core best practices say not to block async code with Task.Wait or Task.Result, and that using async void "is ALWAYS a bad practice in ASP.NET Core apps."
Find blocking and unsafe async patterns in this C# code:
{{code}}
Look for: .Result, .Wait() and GetAwaiter().GetResult() on tasks; async void methods (other than event handlers); Task.Run wrapped around synchronous code and immediately awaited; synchronous I/O such as ReadToEnd on request bodies; and missing CancellationToken parameters.
For each, explain the runtime effect (deadlock, thread pool starvation, unobserved exception) and show the fix. Make the whole call chain async and pass the CancellationToken through.
5. Move background work out of a request
For fire-and-forget code inside controllers or endpoints. Microsoft's guidance is that background tasks should be hosted services, and that work must not capture the request's HttpContext or scoped services like a DbContext.
This ASP.NET Core endpoint starts work that should run in the background:
{{code}}
Rewrite it so that:
- The endpoint returns quickly (for example 202 Accepted) after queuing the work.
- A hosted service processes the queue.
- The background code creates its own dependency injection scope for scoped services such as the DbContext.
- Nothing from HttpContext is captured; copy the values needed before queuing.
- Shutdown is handled: the service stops cleanly when the app stops.
Explain how failures are logged and whether work can be lost on restart.
How do you build ASP.NET Core APIs with AI?
6. Write a minimal API endpoint
For a new endpoint. Asking for validation and error responses up front avoids a second round of fixes.
Write an ASP.NET Core minimal API endpoint for {{operation:creating an order}}.
Target: {{target_framework:net10.0}}. Data access: {{data_access:EF Core}}.
- Use a request record and a response record; do not return entities directly.
- Validate input and return 400 with a problem details body on invalid input.
- Return 201 with a Location header on success, 404 or 409 where they apply.
- Accept a CancellationToken and pass it to every async call.
- Group the endpoint with related ones using a route group.
Add an integration test that calls the endpoint over HTTP. List any assumption about the data model.
7. Review HttpClient usage
For code that creates and disposes HttpClient per call. The best practices page says: "Do not create and dispose of HttpClient instances directly," and recommends IHttpClientFactory.
Review how this C# code calls external HTTP APIs:
{{code}}
- Replace any HttpClient created per call with IHttpClientFactory (a typed client if it fits).
- Set a timeout suited to {{api:the payment provider}} and explain the value.
- Pass CancellationToken through every call.
- Handle non-success status codes explicitly and say which errors are safe to retry.
- Deserialize with System.Text.Json and avoid reading large bodies into a single string.
Show the registration in Program.cs and the updated client.
How do you fix EF Core queries with AI?
8. Fix a slow EF Core query
For an endpoint that got slow as data grew. The EF Core efficient querying guide covers projecting only needed columns, limiting results, avoiding N+1 queries from lazy loading, split queries and no-tracking queries.
This EF Core code is slow with {{rows:500,000}} rows:
{{code}}
Generated SQL (from EF logging), if I have it:
{{sql:not captured yet}}
Check for: N+1 queries from lazy loading or loops, loading whole entities when only a few columns are needed, missing Take or pagination, Include chains that cause a cartesian explosion, tracking queries used for read-only data, and filters EF cannot translate that run on the client.
Rewrite the query, explain each change, and suggest any index the database needs, with the reason.
9. Review an EF Core migration before applying it
For a generated migration you are about to run against production.
Review this EF Core migration before I apply it to a production {{database:SQL Server}} database with {{size:a 40 million row Orders table}}.
{{migration_code}}
For each operation, tell me:
- Whether it locks or rewrites a large table, and roughly how risky that is.
- Whether it can lose data (dropped or narrowed columns, renamed columns treated as drop and add).
- A safer sequence if needed, such as adding a nullable column, backfilling in batches, then adding the constraint.
Also say whether the Down method actually reverses the change.
How do you test C# code with AI?
10. Write unit tests
For services and domain logic. Microsoft's testing overview lists MSTest, NUnit, TUnit and xUnit.net as the popular frameworks.
Write unit tests for this C# class using {{framework:xUnit.net}}.
{{code}}
- One test class per class under test; name tests Method_Scenario_ExpectedResult.
- Use hand-written fakes for dependencies unless I say to use a mocking library.
- Cover the normal path, boundaries, null and empty input, and every exception the code throws.
- Use parameterized tests for input variations instead of copy-pasted tests.
- Test async methods with async tests, never .Result.
List any behavior that is hard to test and the refactor that would fix it.
11. Write an integration test for an API
For endpoints where unit tests with fakes are not enough.
Write integration tests for these ASP.NET Core endpoints using {{framework:xUnit.net}}:
{{endpoints}}
- Host the app in memory for tests and call it over HTTP.
- Replace external services with fakes, and use {{database:a real database in a container}} for data access.
- Reset data between tests so they can run in any order.
- Cover success, validation failure, not found and unauthorized cases.
Show the shared test setup once, then the tests.
How do you keep a .NET project healthy?
12. Triage vulnerable NuGet packages
For security warnings on dependencies. The .NET CLI docs say the noun-first dotnet package list form arrived in .NET 10, and that on .NET 9 SDK or earlier you use dotnet list package. Its --vulnerable option lists packages with known vulnerabilities.
Here is the output of dotnet package list --vulnerable --include-transitive for my solution:
{{output}}
Project files (or Directory.Packages.props):
{{project_files}}
For each vulnerable package:
1. Say whether it is a direct or transitive dependency, and which direct package pulls it in.
2. Give the smallest version change that fixes it, and whether it crosses a major version.
3. If a transitive package needs an override, show how to pin it.
Order the fixes by severity and risk of breaking changes.
13. Upgrade from .NET 8 to .NET 10
For projects on .NET 8 or .NET 9, which both reach end of support on 10 November 2026.
I am upgrading this solution from {{from:net8.0}} to net10.0.
Project files:
{{project_files}}
Code that uses ASP.NET Core, EF Core or serialization heavily:
{{code}}
1. List the changes needed in project files and package versions.
2. List breaking changes between these versions that could affect this code, and mark which ones I should confirm in Microsoft's official breaking changes docs. Do not guess.
3. Remove any LangVersion override that would now be wrong, and do not set it to latest.
4. Give the commands to build and run all tests after the upgrade.
What should you check before you accept the answer?
AI-written C# tends to fail in the same few places:
- Blocking calls. Search the diff for
.Result,.Wait()andasync void. - Null-forgiving operators. Every
!andnull!the model added hides a possible null. Each needs a reason. - Language version drift. Microsoft's language version docs warn: "Don't set the LangVersion element to latest." Reject answers that do.
- Real builds. Run
dotnet buildanddotnet testyourself, or have an agent run them and paste the output.
For API shape and status codes beyond C#, see the API design prompts. If you also work on the JVM, the Java prompts follow the same pattern.
How do you keep your best C# prompts?
Once a prompt becomes a habit, turn it into a skill so Claude Code or Codex uses it without being asked. The blocking call review and the EF Core query fix are good first candidates. Paste one into the free SKILL.md generator, which runs in the browser with no sign-up, and it becomes a valid SKILL.md.
To keep prompts like these close, save them in Kipt. Your library lives as Markdown in a private GitHub repo you own, each blank stays fillable when you copy, and Cmd+K finds any prompt by name or tag. For more on tests, see the unit test prompts.