How to Code in C#/.NET Using AI
Use an AI assistant to write a C# method, build it with the .NET SDK, and prove it with xUnit tests. Works in Visual Studio, VS Code or Rider.
In short: say the .NET version, use decimal for money, give the method signature and rules, ask for xUnit tests, run dotnet test.
Why C# with AI
C# runs a lot of business software: banking, insurance, retail and government apps. It has strong types and great test tools, so AI mistakes show up fast at build time.
What you need
- .NET SDK 10: the current long-term support version. Check with
dotnet --version. - xUnit: a popular .NET test library. The
xunitproject template sets it up. - IDE + assistant: Visual Studio with Copilot, VS Code with C# Dev Kit + Copilot or Claude Code, or Rider.
How it flows
Install and set up
- Install the .NET 10 SDK from dotnet.microsoft.com (or with the Visual Studio Installer).
- Check:
dotnet --versionshows 10.x. - Create the projects:
dotnet new classlib -n Billing dotnet new xunit -n Billing.Tests dotnet add Billing.Tests reference Billing
Step 1 — the prompt
Write a C# static class Gst in namespace Billing (.NET 10) with Add(decimal price, decimal ratePercent) that returns a tuple (Gst, Total). Round GST to 2 decimals, away from zero. Throw ArgumentOutOfRangeException for a negative price or a rate outside 0–100. Example: Add(1000, 18) returns (180, 1180). Only return the code.
Step 2 — the code (tested here)
Billing/Gst.cs// GST calculator. Built with an AI assistant, then tested.
namespace Billing;
public static class Gst
{
/// <summary>Returns (gst, total) for a price before tax. Rounds to 2 decimals.</summary>
public static (decimal Gst, decimal Total) Add(decimal price, decimal ratePercent)
{
if (price < 0)
throw new ArgumentOutOfRangeException(nameof(price), "Price cannot be negative.");
if (ratePercent < 0 || ratePercent > 100)
throw new ArgumentOutOfRangeException(nameof(ratePercent), "Rate must be 0 to 100.");
decimal gst = Math.Round(price * ratePercent / 100m, 2, MidpointRounding.AwayFromZero);
return (gst, price + gst);
}
}Step 3 — ask for xUnit tests, then run them
Write xUnit tests for Gst.Add: 18% on 1000, rounding on 100.25 at 5%, a bad rate, and a negative price.
using Billing;
using Xunit;
public class GstTests
{
[Fact]
public void Adds18Percent()
{
var (gst, total) = Gst.Add(1000m, 18m);
Assert.Equal(180m, gst);
Assert.Equal(1180m, total);
}
[Fact]
public void RoundsToTwoDecimals() => Assert.Equal(5.01m, Gst.Add(100.25m, 5m).Gst);
[Fact]
public void RejectsBadRate() =>
Assert.Throws<ArgumentOutOfRangeException>(() => Gst.Add(100m, 150m));
[Fact]
public void RejectsNegativePrice() =>
Assert.Throws<ArgumentOutOfRangeException>(() => Gst.Add(-1m, 5m));
}dotnet test
# -> Passed! - Failed: 0, Passed: 4Settings and config
- Turn on nullable checks:
<Nullable>enable</Nullable>in the .csproj (new templates do this). It catches AI null mistakes. - Treat warnings as errors in CI:
dotnet build -warnaserror. - Put your rules (".NET 10, xUnit, decimal for money") in
.github/copilot-instructions.mdorCLAUDE.md.
Good C# prompts (reuse these)
- “Convert this class to a record with init-only properties.”
- “Make this method async and pass a CancellationToken.”
- “Add ILogger logging, but never log card numbers or passwords.”
- “Explain this exception and fix it:” + the top lines of the stack trace.
Watch out (common AI mistakes in C#)
- double for money — ask for
decimal. - Old rules and APIs — tax slabs, old .NET Framework code; say your version.
- Made-up NuGet packages — check on nuget.org.
.Result/.Wait()on async code can deadlock; ask forawait.
Try this yourself: ask AI for a C# grade band, then prove the cases
Hello friends. The live chapter already walked through Billing.Gst with xUnit. This practice is a different fictional workshop called Orchard Gate. You ask an AI for a C# class GradeBand with FromScore for letter grades, add ArgumentOutOfRangeException for scores outside 0..100, and prove the cutoffs. On this drafting machine there is no dotnet SDK, so we did not run dotnet test. We proved the same cases with a tiny Python behavioral twin under pytest: the starter twin failed 5 tests and passed 5, and the fixed twin passed all 10.
नमस्कार मित्रांनो. Live chapter मध्ये Billing.Gst आणि xUnit आधीच आले आहे. हा सराव Orchard Gate नावाच्या वेगळ्या काल्पनिक कार्यशाळेवर आहे. तुम्ही AI कडून GradeBand C# class मागता ज्यात FromScore letter grades काढते, 0..100 बाहेरच्या scores साठी ArgumentOutOfRangeException जोडता, आणि cutoffs सिद्ध करता. या drafting मशीनवर dotnet SDK नाही, म्हणून आम्ही dotnet test चालवले नाही. समान cases छोट्या Python behavioral twin ने pytest खाली सिद्ध केले: starter twin मध्ये 5 fail आणि 5 pass, आणि fixed twin मध्ये सर्व 10 पास.
नमस्ते दोस्तों. Live chapter में Billing.Gst और xUnit पहले आ चुके हैं. यह अभ्यास Orchard Gate नाम की अलग काल्पनिक कार्यशाला पर है. आप AI से GradeBand C# class मांगते हो जिसमें FromScore letter grades निकाले, 0..100 से बाहर scores पर ArgumentOutOfRangeException जोड़े, और cutoffs साबित करें. इस drafting मशीन पर dotnet SDK नहीं है, इसलिए हमने dotnet test नहीं चलाया. वही cases छोटे Python behavioral twin से pytest के तहत साबित किए: starter twin में 5 fail और 5 pass, और fixed twin में सभी 10 पास।
Ravindra Bagale's Tip
Say the .NET version you use, ask for ArgumentOutOfRangeException messages you can assert, and keep a small table such as 90 equals A and 89 equals B. Keep the xUnit file for your machine even when you first prove the same bands with the Python twin.
Ravindra Bagale's Tip – मराठी
तुम्ही वापरत असलेली .NET version prompt मध्ये सांगा, assert करता येतील अशी ArgumentOutOfRangeException messages मागा, आणि 90 म्हणजे A व 89 म्हणजे B सारखी छोटी table ठेवा. Python twin ने आधी सिद्ध केले तरीही तुमच्या मशीनसाठी xUnit file जपून ठेवा.
Ravindra Bagale's Tip – हिंदी
जो .NET version इस्तेमाल करते हो उसे prompt में बताओ, ऐसी ArgumentOutOfRangeException messages मांगो जिन पर assert हो सके, और 90 यानी A तथा 89 यानी B जैसी छोटी table रखो. Python twin से पहले साबित करने पर भी अपनी मशीन के लिए xUnit file बचाए रखो।
dotnet or csharp SDK, and none was installed. The same grade bands were proved with a Python twin under Python 3.13.5 and pytest 9.1.1. Starter twin: 5 failed, 5 passed. Fixed twin: 10 passed. dotnet test was not run. The GradeBandTests.cs file is still the student-facing C# test source.Your task: start from the buggy GradeBand.cs that maps some scores but uses wrong cutoffs and skips validation. Ask an AI to match A through F as listed, throw ArgumentOutOfRangeException outside 0..100 with a message containing 0 and 100, and keep the xUnit file for your machine. On machines without .NET yet, you may also use the Python twin.
Setup
- Create a project folder and open a terminal inside it.
- Optional twin setup: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - Activate it: on macOS or Linux run
source .venv/bin/activate. In Windows Command Prompt run.venv\Scripts\activate.bat, and in Windows PowerShell run.venv\Scripts\Activate.ps1. - Install pytest inside the virtual environment:
python -m pip install pytest.
Extra for C# on your machine: install the .NET SDK 8 or newer, confirm dotnet --version, and run dotnet test with the xUnit file. This drafting box did not have a .NET SDK and did not install one.
Starter GradeBand.cs (wrong cutoffs, skips validation):
// Orchard Gate Workshop grade band helper (fictional teaching school — not a real institution).
// Starter: returns a letter for a few scores but skips validation and wrong cutoffs.
namespace OrchardGate;
public static class GradeBand
{
/// <summary>Map a percent score 0..100 to a letter grade.</summary>
public static string FromScore(int score)
{
// Starter bugs: no range check; wrong bands (A only at 95+, etc.).
if (score >= 95) return "A";
if (score >= 80) return "B";
if (score >= 60) return "C";
if (score >= 40) return "D";
return "F";
}
}
xUnit tests GradeBandTests.cs (for your dotnet test run later):
// xUnit-style cases for Orchard Gate GradeBand (run with `dotnet test` on your machine).
// This drafting box has no .NET SDK — see the Python twin for local proof.
using System;
using Xunit;
using OrchardGate;
public class GradeBandTests
{
[Theory]
[InlineData(100, "A")]
[InlineData(90, "A")]
[InlineData(89, "B")]
[InlineData(80, "B")]
[InlineData(70, "C")]
[InlineData(60, "D")]
[InlineData(59, "F")]
[InlineData(0, "F")]
public void MapsKnownBands(int score, string expected)
{
Assert.Equal(expected, GradeBand.FromScore(score));
}
[Fact]
public void RejectsBelowZero()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => GradeBand.FromScore(-1));
Assert.Contains("0 and 100", ex.Message);
}
[Fact]
public void RejectsAboveOneHundred()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => GradeBand.FromScore(101));
Assert.Contains("0 and 100", ex.Message);
}
}
Python twin grade_band.py (optional local proof matching the same cases):
"""Behavioral twin of OrchardGate.GradeBand.FromScore (starter — buggy cutoffs)."""
def from_score(score: int) -> str:
if not isinstance(score, int) or isinstance(score, bool):
raise TypeError("score must be an int")
# Starter bugs: no range check; wrong A threshold.
if score >= 95:
return "A"
if score >= 80:
return "B"
if score >= 60:
return "C"
if score >= 40:
return "D"
return "F"
pytest twin test_grade_band.py:
"""pytest twin for Orchard Gate GradeBand (same cases as GradeBandTests.cs)."""
import pytest
from grade_band import from_score
@pytest.mark.parametrize(
"score,expected",
[
(100, "A"),
(90, "A"),
(89, "B"),
(80, "B"),
(70, "C"),
(60, "D"),
(59, "F"),
(0, "F"),
],
)
def test_maps_known_bands(score, expected):
assert from_score(score) == expected
def test_rejects_below_zero():
with pytest.raises(ValueError, match="0 and 100"):
from_score(-1)
def test_rejects_above_one_hundred():
with pytest.raises(ValueError, match="0 and 100"):
from_score(101)
Suggested AI ask (copy and adapt):
csharp-prompt.txtWrite a C# static class OrchardGate.GradeBand with public static string FromScore(int score). Throw ArgumentOutOfRangeException when score is outside 0..100; the message must contain "0 and 100". Map 90-100 to A, 80-89 to B, 70-79 to C, 60-69 to D, and 0-59 to F. Add xUnit Theory cases for those cutoffs plus two Fact cases for -1 and 101. Fictional Orchard Gate Workshop teaching only.
HOW to finish
- Save the starter C# file, the xUnit file, and optionally the Python twin files.
- Ask your AI assistant to fix the bands and add the out-of-range exception.
- Run xUnit with
dotnet teston your machine when the SDK is ready. - Optional twin:
python -m pytest -q test_grade_band.pywith the fixed Python twin. Expect 10 passed. The buggy twin was measured here as 5 failed, 5 passed.
Real pytest twin output after the fixed Python mirror:
pytest-after.txt.......... [100%]
10 passed in 0.01s
Optional completed GradeBand.cs (try it yourself first)
Your AI assistant may reorder the checks. Any version is fine if the xUnit cases or the pytest twin pass.
GradeBand.cs// Orchard Gate Workshop grade band helper (fictional teaching school — not a real institution).
namespace OrchardGate;
public static class GradeBand
{
/// <summary>
/// Map a percent score 0..100 to a letter grade.
/// A: 90-100, B: 80-89, C: 70-79, D: 60-69, F: 0-59.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">When score is outside 0..100.</exception>
public static string FromScore(int score)
{
if (score < 0 || score > 100)
throw new ArgumentOutOfRangeException(nameof(score), "score must be between 0 and 100");
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
if (score >= 60) return "D";
return "F";
}
}
Fixed Python twin for local proof:
grade_band.py"""Behavioral twin of OrchardGate.GradeBand.FromScore (fixed)."""
def from_score(score: int) -> str:
if not isinstance(score, int) or isinstance(score, bool):
raise TypeError("score must be an int")
if score < 0 or score > 100:
raise ValueError("score must be between 0 and 100")
if score >= 90:
return "A"
if score >= 80:
return "B"
if score >= 70:
return "C"
if score >= 60:
return "D"
return "F"
Troubleshooting
- Problem: score 90 returns B. Fix: A must start at 90 inclusive, so change the A threshold from 95 to 90.
- Problem: score 59 returns D. Fix: F covers 0 through 59, and D covers only 60 through 69.
- Error:
dotnet: command not found. Fix: install the .NET SDK on your machine, or prove the same bands first with the Python twin. This drafting box had no SDK and did not install one. - Problem: negative scores still return a letter. Fix: throw
ArgumentOutOfRangeExceptionbefore the bands, with a message that contains0 and 100.
Practice cards: English and spoken Marathi
Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.
Name the bands in the prompt
Keep xUnit even if you use a twin
Prompt मध्ये bands सांगा
Twin वापरला तरी xUnit ठेवा
Quick quiz
1. Which type should you use for money in C#?
decimal.
2. How do you run xUnit tests from the terminal?
dotnet test.
3. What does Gst.Add(1000, 18) return?
(180, 1180).
4. What old fact did the AI get wrong in this chapter?
It used the old GST slabs (12% and 28%) that changed in September 2025.
Save tokens and money
Paste one class, not the whole solution or bin/obj folders. Paste only the first lines of a stack trace. Let the IDE do free refactors (rename, extract method) and ask the AI only for logic and tests.