跳到正文
DEV Community· Khaja Hussain·· 1 小時前AI 評分60

C# 15 與 .NET 11 十分鐘速成:主要更新及程式示例

C# 15 and .NET 11 Crash Course: Everything You Need in 10 Minutes

AI 導讀

Khaja Hussain 撰寫 C# 15 與 .NET 11 快速入門,整理語言及平台更新,並以程式碼示例説明用法。C# 15 重點包括支援窮盡檢查的聯合型別、封閉階層、集合運算式參數、擴充索引器及標籤式 break/continue;記憶體安全功能仍屬預覽版。

正文

.NET 11 and C# 15 landed on November 10, 2026, and this one is a big deal. Why? Because C# finally has union types. Yes, the feature we've been begging for since roughly forever.

If you're a busy C# dev and just want the short version, grab a coffee ☕. This is everything you need in about 10 minutes: what changed, what the code looks like, and when you'd actually use it.

Before we start

You'll need:

  • The .NET 11 SDK (download it here)
  • Visual Studio 2026, VS Code with C# Dev Kit, or Rider (whatever makes you happy)
  • A project targeting net11.0

Good news: C# 15 is the default language version for net11.0, so you don't have to touch LangVersion.

<PropertyGroup>
  <TargetFramework>net11.0</TargetFramework>
</PropertyGroup>

Alright, let's dig in.


1. Union types (the star of the show)

Be honest. How many times have you faked "this value can be A, B, or C" with a base class, the OneOf library, or an object and a pile of casts? Same here.

Here's the old way most of us wrote it:

// Before: "trust me, it's one of these"
object result = GetPet();
if (result is Dog dog) { /* ... */ }
else if (result is Cat cat) { /* ... */ }
// Forgot Bird? The compiler won't tell you. 🙃

Now it's just part of the language:

public record class Cat(string Name);
public record class Dog(string Name);
public record class Bird(string Name);

public union Pet(Cat, Dog, Bird);

You can assign any of the case types directly, because they convert to the union automatically:

Pet pet = new Dog("Rex");

string name = pet switch
{
    Dog d  => d.Name,
    Cat c  => c.Name,
    Bird b => b.Name,
};

Here's the part I love: the compiler checks that your switch handles every case. Add a Fish to the union six months from now, and every switch that forgot about it gets flagged. No more "oops, we never handled that" bugs showing up in production.

Where this really shines: API results

This is the pattern I think most of us will use first:

public record Product(int Id, string Name, decimal Price);
public record NotFound(int Id);
public record OutOfStock(int Id, DateOnly RestockDate);

public union ProductResult(Product, NotFound, OutOfStock);

ProductResult GetProduct(int id) =>
    id switch
    {
        1 => new Product(1, "Keyboard", 49.99m),
        2 => new OutOfStock(2, new DateOnly(2026, 12, 1)),
        _ => new NotFound(id),
    };

IResult ToHttp(ProductResult result) => result switch
{
    Product p    => Results.Ok(p),
    NotFound n   => Results.NotFound($"Product {n.Id} not found"),
    OutOfStock o => Results.Conflict($"Back on {o.RestockDate}"),
};

No exceptions for control flow. No surprise nulls. Every outcome is right there in the type, and the compiler has your back.

One more tiny example: a login result

public record LoggedIn(string UserName);
public record WrongPassword(int AttemptsLeft);
public record LockedOut(DateTime Until);

public union LoginResult(LoggedIn, WrongPassword, LockedOut);

string message = result switch
{
    LoggedIn ok      => $"Welcome back, {ok.UserName}! 👋",
    WrongPassword wp => $"Oops, wrong password. {wp.AttemptsLeft} tries left.",
    LockedOut lo     => $"Too many tries. Come back after {lo.Until:t}.",
};

Read it once and you know every way a login can end. That's the whole point.

Reach for it when a method can end in a few different ways: success, not found, validation failed, and so on.

📖 Union types in the docs


2. Closed hierarchies

Maybe you like good old class hierarchies, but you still want that "did you handle every case?" check. That's what closed is for:

public closed record class GateState;
public record class Closed : GateState;
public record class Open(float Percent) : GateState;

string Describe(GateState state) => state switch
{
    Closed            => "closed",
    Open(var percent) => $"{percent}% open",
    // No warning: every direct child of GateState is handled.
};

A few rules worth knowing so they don't bite you later:

  • A closed class can only be inherited inside the same assembly.
  • It's automatically abstract, so you can't mix it with sealed, static, or abstract.
  • It's not transitive. Want exhaustive checks deeper in the tree? Mark those middle classes closed too.

So which one do I pick? Here's how I think about it:

Go with a union when... Go with a closed hierarchy when...
The types are unrelated or already exist The cases share a base type and behavior
You're combining types you don't own You own the whole model

3. Collection expression arguments

Collection expressions ([1, 2, 3]) are lovely, but there was always one annoying gap: you couldn't pass constructor arguments like a capacity or a comparer. That's fixed now. Just put with(...) as the first element.

Before, you had to fall back to the old style:

// Before
var tags = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "csharp", "CSharp" };

Now:

// After
HashSet<string> tags = [with(StringComparer.OrdinalIgnoreCase), "csharp", "CSharp"];
// tags.Count == 1, because case doesn't matter

And pre-sizing a list when you already know roughly how big it'll get:

string[] values = ["one", "two", "three"];

List<string> names = [with(capacity: values.Length * 2), .. values];

Tiny feature, but I have a feeling you'll use it every week.


4. Extension indexers

C# 14 gave us extension blocks. C# 15 lets you put indexers inside them:

public static class SequenceIndexer
{
    extension(IEnumerable<int> sequence)
    {
        public int this[int index] => sequence.ElementAt(index);
    }
}

IEnumerable<int> numbers = Enumerable.Range(1, 10);
int third = numbers[2]; // 3

Here's a more everyday one. Grab a config value with a fallback, right from the indexer:

public static class ConfigExtensions
{
    extension(IDictionary<string, string> settings)
    {
        public string this[string key, string fallback] =>
            settings.TryGetValue(key, out var value) ? value : fallback;
    }
}

var settings = new Dictionary<string, string> { ["Theme"] = "Dark" };

string theme = settings["Theme", "Light"];     // "Dark"
string lang  = settings["Language", "en-CA"];  // "en-CA"

One catch: the receiver (sequence or settings here) has to be a named parameter, because indexers are always instance members.

⚠️ A friendly warning: ElementAt on an IEnumerable can walk the whole sequence. Nicer syntax doesn't make it any faster, so don't drop this into a hot loop.


5. Labeled break and continue

You know that awkward bool found = false; dance to get out of nested loops? Or the goto you felt slightly guilty about? Here's the "before" we've all written:

// Before
bool found = false;
foreach (var order in orders)
{
    foreach (var item in order.Items)
    {
        if (item.Sku == "ABC-123") { found = true; break; }
    }
    if (found) break; // easy to forget this line!
}

And now:

// After
search: foreach (var order in orders)
{
    foreach (var item in order.Items)
    {
        if (item.Sku == "ABC-123")
            break search; // done, out of both loops
    }
}

It works with continue too:

outer: for (int row = 0; row < grid.Height; row++)
{
    for (int col = 0; col < grid.Width; col++)
    {
        if (grid[row, col].IsBlocked)
            continue outer;   // jump to the next row

        if (grid[row, col].IsGoal)
            break outer;      // get out of both loops
    }
}

Put the label right on the loop (or switch). Plain break and continue work exactly like they always did. Bonus: the new IDE0410 analyzer will point out old flag or goto patterns you can clean up.


6. Static helpers in interfaces on older runtimes

This one is small but handy. Non-virtual static members with a body now work in interfaces even if you target older runtimes:

public interface IMeasurement
{
    public static double ToMeters(double centimeters) => centimeters / 100;
}

double meters = IMeasurement.ToMeters(250);

Just keep in mind that default instance implementations, static abstract, and static virtual members still need runtime support.


7. Memory safety (preview, so look but don't ship)

C# 15 starts rethinking what unsafe means. Instead of just saying "pointers live here", it becomes a contract that callers have to respect. It's still a preview, so please keep it out of production for now.

If you're curious and want to play with it:

<PropertyGroup>
  <LangVersion>preview</LangVersion>
  <Features>$(Features);updated-memory-safety-rules</Features>
  <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

The highlights:

  • Declaring pointers, taking & addresses, fixed, and sizeof no longer need an unsafe context.
  • Dereferencing (*p, p->x, p[i]) still does.
  • There's a new unsafe(expression) for one-off expressions, like in a field initializer.
  • Marking a member unsafe means callers need an unsafe context too.

If you don't write low-level code, feel free to skip this one. You won't miss much yet.


The rest of .NET 11, in a nutshell

  • Runtime async. The runtime now handles async suspend and resume itself, instead of leaning only on compiler-generated state machines. You don't change a line of code, you just get the performance benefits over time.
  • A snappier CLI. dotnet commands start from a Native AOT host, and the MSBuild server sticks around between builds. Your build-and-test loop should feel quicker.
  • ASP.NET Core 11. You get async validation, and OpenAPI docs now default to OpenAPI 3.2. ⚠️ Heads up: that default counts as a breaking change, so double-check your client generators and Swagger tooling.
  • .NET MAUI. CoreCLR is now the default runtime.
  • AI and agents. There's a built-in MCP server project template and new Blazor components for chat-style AI interfaces.
  • EF Core 11 ships right alongside everything else.

📖 What's new in .NET 11 · What's new in ASP.NET Core 11


⚠️ So... should you upgrade?

Honestly, this part matters more than any shiny feature:

  • .NET 8 and .NET 9 hit end of support on November 10, 2026. That means no more security patches.
  • .NET 10 is LTS (long-term support). It's the safe bet for production.
  • .NET 11 is STS (standard-term support), supported for 24 months, until November 2028.

My take:

  1. Still on .NET 8 or 9? Move to .NET 10 soon. This one is about security, not features.
  2. Starting something new, or just really want union types? .NET 11 is a great pick.
  3. Big enterprise app? Stay on .NET 10 and plan for the next LTS.

TL;DR cheat sheet

Feature In one line
Union types public union Pet(Cat, Dog, Bird); with exhaustive switch
Closed hierarchies public closed record class Shape; same assembly only
Collection args [with(capacity: 10), .. items]
Extension indexers this[int i] inside an extension(...) block
Labeled jumps break outer; / continue outer;
Memory safety Preview, opt-in, new unsafe contract model

Wrapping up

If you only try one thing from this release, make it union types. Here's an easy way to start: find one method in your codebase that returns null or throws when something isn't found, and turn it into a union result. I think you'll feel the difference right away.

Your turn 💬

If you're a .NET fan like me, I'd really love to hear from you! Drop a comment and tell me:

  • 🥇 Which C# 15 feature are you trying first?
  • 🙌 Were you waiting for union types too, or are you happy sticking with OneOf?
  • 🤔 What's one feature C# still needs?

Even a quick "union types, finally!" makes my day. 😄

And if this saved you some time, hit the ❤️ and share it with your team. Happy coding, and see you in the comments! 👇

References

來源:DEV Community · dev.to