Skip to content

C# for the AI Age ​

In this AI age, should you still care about the programming language? The runtime? Why not write everything in Rust?

These are questions that many teams are probably asking themselves now as AI coding has exploded since I first wrote this guide. In the past, developer coming from a TypeScript background would likely have been reluctant to write Rust because of the lift in both syntax and runtime model. Now with AI, those are less of a concern.

But perhaps teams should consider an alternate: now that a team can write code in any language and runtime, should they choose C# and .NET?

The answer is yes teams should consider C# more than ever in the AI age.

Human Review is Still Useful ​

You might have deduced it by now πŸ˜… but TypeScript and C# are quite similar and if you can read one, then you can largely read the other.

But if you need to review some code that an agent writes in Rust or Go with no background in either language, would you feel comfortable being able to read the code?

If you believe that humans still need to review the code, even if minimally, then choosing a language that is familiar enough is still a big win when it matters.

As you'll see throughout this guide, C#'s framework level components are also quite familiar and easy to understand if you are coming from Express, Nest.js, or even Elysia.js. This ensures that code can still be grokked by a human when needed.

See:

The Agentic Inner Loop ​

In the agentic era, one of the keys of building an "agent-friendly" codebase is to speed up "the inner loop".

This describes how quickly a coding agent can get feedback on source code generation. The faster an agent can iterate and receive a signal, the faster and more efficiently the agent can work.

The loop has different layers with different characteristics:

LoopCostWhy?
Inner: Types, linters, and analyzersLowThese run fast and provide rapid feedback. Typed languages with linters and analyzers provide agents a fast mechanism to statically verify the code. Type-optional, duck-typed languages benefit from adopting typed variants (e.g. JS vs TS) as well as schema packages (e.g. Zod, Valibot, Pydantic, etc.)
Middle: BuildModerateA build pass can expose type errors, but full builds can be costly compared to running a type check, a linter, or an analyzer.
Outer: RunHighRunning the application to verify is the most costly. E2E and integration tests that require the running application are not only slower, but can be harder to coordinate and reduce concurrency as passes may require serialization of scenarios. Languages that have strong enforcement of static type checks can reduce the chance/rate of errors at this layer through the type system itself.

When evaluated through this lens, C# emerges as a very strong contender.

Type Safety ​

Unlike JavaScript and Python, C# is not type-optional. Unlike TypeScript's structural typing, C# requires nominal named types across public boundaries (and object can be avoided with analyzer rules).

This improves the confidence in verification via static analysis as type inference is always backed by explicitly declared types (whereas TS can lean back to inferred types).

Research shows that agents benefit from types because it provides them an early signal of correctness:

Why AI is pushing developers toward typed languages

With AI tools and agents producing larger volumes of code and features than ever, it only makes sense that reliability is more critical. And… that is where typed languages win the debate. Not because untyped languages are β€œbad,” but because types catch the exact class of surprises that AI-generated code can sometimes introduce.

Language Plasticity is More Important Than Ever

Dynamic languages shine for rapid iteration, but their flexibility can demand extra tokens from the LLM. In duck-typed environments like Python or JavaScript, a variable’s behavior emerges only through usage. When an LLM builds context, it often needs surrounding code, comments, or explicit hints to infer β€œthis variable quacks like a list here, but might be something else later.”

Statically typed languages flip the script. In D, a parameter declared as int[] arr or a struct with explicit methods tells the model exactly what operations are valid, right there in the signature. No detective tokens required.

The result? When using LLMs with duck-typed languages, the model often spends more tokens reconstructing intent. Explicit types and consistent call-site semantics in D let it focus on logic instead of inference.

Strongly Typed Languages Yield Lower Perplexity in Code Completion Across Eighteen Models

In an extensive empirical investigation into how automated software engineering tools process source code, researchers have demonstrated that large language models exhibit systematically higher confidence when predicting tokens in strongly typed programming languages than in dynamically typed scripting languages.

By analyzing a curated, balanced corpus of 2,254 source files harvested from 881 open-source GitHub projects, the authors established that languages enforcing formal type disciplines, most notably Java, Go, and C#, consistently yield lower perplexity scores than flexible scripting environments such as Perl, Ruby, and Shell.

Especially when reading snippets of AI generated diffs, having explicit types makes it easier for the human reader to have the necessary context to understand the code (versus inferred, interpolated (Pick, Omit), inline, or anonymous types that are common with TypeScript).

πŸ”‘ Key takeaway

Explicit types help agents get early signals of incorrect code. C# 15 union types, closed hierarchies, and switch expressions are powerful tools for agents.

Entity Framework Core (EF Core) is Even More Powerful ​

EF Core has always been one of the biggest draws of .NET for building business applications heavy in CRUD (see Databases and ORMs).

It models the Unit of Work pattern, provides typed runtime queries, performs nearly as well as hand-rolled SQL, and is still flexible enough to be used with raw SQL when needed.

csharp
// Every property and join is checked by the compiler against the entity model
var seniors = await db.Candidates
  .Where(c => c.Yoe >= 5 && c.Position.IsOpen)
  .OrderByDescending(c => c.Yoe)
  .Select(c => new CandidateSummary(c.Email, c.Position.Title))
  .ToListAsync(ct);

// Unit of Work: track changes and commit in one transaction
db.Candidates.Add(new Candidate { Email = "ada@example.com", Yoe = 10 });
await db.SaveChangesAsync(ct);

// db.Candidates.Where(c => c.YearsOfExp >= 5) // ❌ Caught at compile time

In the agent era, EF Core's code-first approach is a big bonus because it allows for build-time checks against the database schema (effective to degrees, of course).

This allows agents to write analyzer and compile time checked code and perform verification before running expensive integration tests.

Verification via Roslyn Analyzers ​

C# is also a bit unique in that its compiler (Roslyn) itself is written in C#!

The Roslyn compiler allows static and compile-time introspection of the code via analyzers that can examine the code and suggest fixes.

This is an extremely powerful tool to enforce correct patterns in agent generated code through the compiler.

πŸ”‘ Key takeaway

Roslyn analyzers allow writing C# to verify C# and enforce best practices and patterns, giving agents powerful tools to verify code statically.

Source Generators ​

Source generators take advantage of Roslyn to dynamically produce C# code. This is extremely useful for agents because it allows for a significant reduction in boilerplate which helps save context.

It also simplifies the pattern understanding that an agent needs when adding new code because complex wiring can be reduced to just an attribute or the presence of a marker interface.

For example, with .NET's built-in [LoggerMessage] generator, the agent only writes the attribute and a partial method signature:

csharp
// πŸ“„ CandidateLog.cs (what the agent writes)
public static partial class CandidateLog {
  [LoggerMessage(LogLevel.Information, "Created {Email} ({Yoe} yrs)")]
  public static partial void Created(this ILogger log, string email, int yoe);
}

At compile time, Roslyn emits the zero-allocation implementation into CandidateLog.g.cs:

csharp
// πŸ“„ CandidateLog.g.cs (generated at compile time)
partial class CandidateLog {
  private static readonly Action<ILogger, string, int, Exception?> _created =
    LoggerMessage.Define<string, int>(
      LogLevel.Information,
      new EventId(1, nameof(Created)),
      "Created {Email} ({Yoe} yrs)"
    );

  public static partial void Created(this ILogger log, string email, int yoe) {
    if (log.IsEnabled(LogLevel.Information)) {
      _created(log, email, yoe, null);
    }
  }
}

Generators were traditionally a relatively niche technique used mostly by more advanced teams, but AI makes them a broadly accessible tool for teams to write low-boilerplate, high-performance code (reflection free!).

πŸ”‘ Key takeaway

Source generators are beneficial for agents because they remove boilerplate and thus reduce both tokens-in as well as expensive tokens-out!

CSharpRepl ​

One of the biggest "hacks" that the .NET platform has for agentic coding is the CSharpRepl "hack".

CSharpRepl is a commandline REPL that lets developers (or agents!) write C# in a CLI and execute it in a read-eval-print-loop.

On its own, this gives agents a fast utility to write throwaway code without overhead. However, what if it were possible to directly REPL into a running application?

What if it were possible to wrap or replace running, executable code at the function level? This would be insane because that means an agent can literally "touch" the insides of a running application (including in memory state) and manipulate it in all dimensions!

In fact, this is exactly what CSharpRepl can do and it gives agents superpowers when it comes to diagnosing runtime issues (no rebuild! read the running state!) and rapidly iterating.

Check out the original blog post by the library author: Injecting a C# REPL into a running .NET process

πŸ”‘ Key takeaway

CSharpRepl is a very unique tool and allows agents to freely manipulate the running application code without rebuilding while maintaining runtime state. This allows agents to rapidly iterate and easily diagnose runtime issues that require state.

Tooling and Platform Stability ​

The JS/TS ecosystem is notorious for the variety of tooling available. Node, Deno, Bun; tsc, swc, oxc; npm, yarn, pnpm; cjs vs esm. Python as well has a variety of tools like uv, pip, pixi, and others.

.NET's all-in-one dotnet has been stable, well documented, and reduces the choices and ambiguity in the workspace.

The language and platform have also been remarkably stable since the .NET Framework and .NET Core split with retention of feature support being extremely high (to the extent that many consider C#'s keyword space to be bloated).

While Rust is all the rage, .NET still has many benefits for teams that want to move fast. Hot reload, fast incremental builds, great platform tooling, and good ergonomics still make it a great choice for backend web APIs.

Aspect.NET (C#)Rust
Clean builds & dependenciesFast. NuGet restores pre-compiled .dll assemblies, so dotnet build only compiles your code into lightweight IL.Slower. Cargo compiles every crate dependency (often 200+ crates for a web stack) from source through LLVM.
Edit-compile-test loopFast incremental dotnet build and dotnet test, plus built-in dotnet watch hot reload.cargo check is fast (skips LLVM), though cargo test still pays codegen and linking; no built-in hot reload.
Package management & stdlibdotnet + NuGet + large first-party stdlib (HTTP, DI, JSON, OpenAPI, logging, auth, crypto included).Cargo + crates.io is great, though a small stdlib means pulling third-party crates for async runtimes, HTTP, and serialization.
Ergonomics & reviewabilityGarbage-collected with TypeScript-like syntax; low friction for business logic and human review.Borrow checker, lifetimes, and async Send/Sync bounds enforce safety at compile time, with higher friction for CRUD/API code.
MetaprogrammingRoslyn analyzers and incremental source generators are written in plain C# and run inside the compiler and IDE.Procedural macros compile as separate crates (serializing the build graph) and are harder to debug.
Runtime profileNear-native throughput via RyuJIT (or Native AOT for fast cold starts), with GC overhead on tiny targets.Peak native performance, minimal memory footprint, and deterministic latency with no GC pauses.

Rust will offer the highest performance with the lowest resource usage, but .NET offers many benefits for teams building CRUD backend web APIs.

πŸ”‘ Key takeaway

.NET's unified tooling and stable surface area means that agents need less guidance and fewer tool calls (e.g. using CLI to introspect) because of the stability of the platform.

Performance, Capacity, and Throughput ​

Something that doesn't change is that C# is still fast. In fact, I would make the case that AI generated C# has a high chance of being faster than hand-rolled C# because the advanced techniques are now more accessible than ever. From using array pools to Span<T> to unmanaged memory to System.Threading.Channels; techniques that would have required more expertise in the past to use are now within reach of every developer.

The .NET runtime is very competitive and up there with Rust and Go. Why does this matter? At the end of the day, runtime performance (in terms of request throughput) and efficiency (in terms of memory usage) result in a more compact infrastructure footprint for the same volume and cost.

For example, comparing Hono and ElysiaJS on Bun, Carter on .NET minimal web APIs, FastAPI on Python, and Spring Boot on Java across key HttpArena HTTP/1.1 throughput profiles (each cell lists requests per second and p99 latency, with RAM on the second line; the throughput leader is in bold and the memory winner is in bold italic):

ProfileHono (Bun)Elysia (Bun)Carter (.NET)FastAPI (Python)Spring Boot (Java)
Baseline (4,096 conns)1,305,614, 8.60ms
1.8 GiB
1,446,994, 8.58ms
1.9 GiB
1,398,551, 7.62ms
344 MiB
298,664, 21.30ms
4.9 GiB
259,473, 16.10ms
2.5 GiB
Short-lived (4,096 conns)1,157,751, 12.30ms
1.8 GiB
1,264,437, 11.90ms
1.9 GiB
460,816, 12.30ms
117 MiB
273,929, 79.20ms
6.2 GiB
208,860, 18.20ms
2.4 GiB
Async Delay (32,000 conns)991,391, 58.50ms
6.1 GiB
1,155,316, 47.40ms
5.8 GiB
942,839, 85.80ms
1.4 GiB
190,420, 284.60ms
6.0 GiB
19,167, 1.11s
1.3 GiB
JSON Comp (4,096 conns)58,990, 154.40ms
9.6 GiB
322,182, 29.60ms
2.2 GiB
395,625, 36.00ms
573 MiB
101,178, 537.40ms
5.1 GiB
198,628, 20.10ms
2.4 GiB
JSON Comp (16,384 conns)53,102, 568.40ms
13.0 GiB
330,432, 81.80ms
2.5 GiB
382,893, 67.60ms
856 MiB
98,959, 717.50ms
5.2 GiB
183,986, 55.90ms
2.6 GiB
JSON TLS (4,096 conns)627,740, 145.45ms
2.7 GiB
925,608, 36.49ms
1.9 GiB
566,579, 130.50ms
878 MiB
133,489, 131.52ms
5.1 GiB
188,030, -
3.2 GiB

Notice that Carter takes both compressed JSON profiles (ahead of Elysia, Hono, Spring Boot, and ~4x FastAPI) and wins memory on 5 of the 6 throughput profiles.

Now look at Latency-10K (a steady 10,000 requests per second over 1,024 connections), which is closer to a typical production workload than a saturation test:

Latency-10KHono (Bun)Elysia (Bun)Carter (.NET)FastAPI (Python)Spring Boot (Java)
Score37.434.649.928.750.5
p99513us660us118us590us184us
CPU734.4% (~7.3 cores)857.9% (~8.6 cores)130.2% (~1.3 cores)274.3% (~2.7 cores)82.9% (~0.8 cores)
RAM1.6 GiB1.7 GiB153 MiB4.9 GiB510 MiB

πŸ”‘ Key takeaway

C# offers a great balance of ergonomics and approachability while competing very favorably with Rust and Go (Java memory consumption is off the charts...). For high throughput applications, a C# backend will net lower spend versus Node or Java. In the AI age, you should seriously consider avoiding Python for CRUD APIs.

AI Exploits and Supply Chain Hacks ​

GitHub's State of the Octoverse 2020 highlighted the discrepancy in the number of alerts surfaced by Dependabot as a percentage of the active projects in a package manager ecosystem (e.g. NPM, NuGet).

It turns out, the .NET ecosystem has one of the lowest average transitive dependencies (attack surface) and one of the lowest rates of alerts.

Aside from that, because of its wide enterprise adoption as well as first party support from Microsoft, it has a long history of being patched expediently when vulnerabilities are detected. One other advantage is that .NET's massive first party standard libraries and SDKs means that many important dependencies are professionally maintained.

This is a big bonus in an era when exploits have exploded on the back of adversarial AI and software has to defend against multiple vectors of ingress from supply chain to bug exploits.

πŸ”‘ Key takeaway

C#, .NET, and the large set of first-party dependencies get regular security updates and have highly controlled deploys. It is still possible to suffer supply chain attacks, but the low rate of transitive dependencies, large set of first party libraries, and professional engineers behind it improve the security profile of the platform.

Shift in the Ecosystem Challenge ​

Traditionally, one of the biggest draws of the Node ecosystem has been the breadth of libraries and packages available. .NET has been a smaller ecosystem of packages that have high community concentration (meaning many projects use the same defaults). Because C# is heavily adopted in enterprise, the ecosystem has not been as rich in open source projects.

However, I sense that the paradigm is changing now. Like other ecosystems, C# is seeing a surge of open source projects from developers now empowered by AI. But more importantly, the gap in ecosystem size is less important than ever because AI can build the necessary tooling, tuned to the needs of the team.

πŸ”‘ Key takeaway

.NET's OSS ecosystem (few, high community concentration) has often left gaps compared to the richness of the Node ecosystem (many, low community concentration) which made it less attractive when packages were available off the shelf. However, agents can now bridge that gap easily.

Closing Thoughts ​

The debate on whether programming languages matter seems misguided in some respects.

For certain, aspects like the type system as well as support for static analysis improve agent performance. Platform capabilities like source generation allow agents to reduce both context in and out. And having a professionally maintained, secure framework and runtime means that teams reduce exposure to rapid, AI-assisted software exploits.

In this era, I think teams should strongly reconsider .NET and C# as an alternative to TypeScript or Python on the backend for high-volume, production systems.

Read More ​

If you'd like to see more writing on this, check out:

The Unexpected AI Stack

This series walks through a "clean-room", ground-up setup of a modern .NET codebase optimized for AI to iterate with a fast inner loop.

It is designed to help teams understand each of the technical decisions that go into the scaffolding so that teams understand the underlying reasoning and mechanics instead of a set of mystery skills.

Ready to Dive In? ​

If any of this rang true to you, let's dive in and see why C# and .NET might be right for your team!