[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78896GVN7QVPMH50XNBB8JS":3,"skill-same:01M78896GVN7QVPMH50XNBB8JS":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":29,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M78896GVN7QVPMH50XNBB8JS","csharp-15",null,"Write, review and modernize C# 15 (.NET 11) code correctly. Covers every C# 15 feature - collection expression arguments (`[with(...), ...]`), union types (`union`, `[Union]`, `IUnion`, custom unions), closed class hierarchies (`closed`), extension indexers, labeled `break`\u002F`continue`, non-virtual static interface members on runtimes without default interface methods, and the preview memory-safety model (`unsafe(expr)`, `safe`, requires-unsafe members). Use when code targets net11.0 or LangVersion 15\u002Fpreview, when the user mentions any of these features, when replacing marker interfaces, OneOf-style results, `goto`\u002Fflag loop exits or capacity\u002Fcomparer boilerplate, or when the build reports CS8121, CS8509, CS8655, CS8510, CS0121\u002FCS0411 on a `with(...)` element, CS9370, CS9380 or CS9363.","hmlendea\u002Fgithub-copilot-memories","hmlendea","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F10261133?v=4","01M7888TTHZ7DJMARYVZ19K28T","Horațiu Mlendea","01M7888TVMZHRCJB31TBG3TMSK",0,"GPL-3.0","https:\u002F\u002Fgithub.com\u002Fhmlendea\u002Fgithub-copilot-memories\u002Fblob\u002Fmaster\u002Fskills\u002Fcsharp-15\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: csharp-15\ndescription: Write, review and modernize C# 15 (.NET 11) code correctly. Covers every C# 15 feature - collection expression arguments (`[with(...), ...]`), union types (`union`, `[Union]`, `IUnion`, custom unions), closed class hierarchies (`closed`), extension indexers, labeled `break`\u002F`continue`, non-virtual static interface members on runtimes without default interface methods, and the preview memory-safety model (`unsafe(expr)`, `safe`, requires-unsafe members). Use when code targets net11.0 or LangVersion 15\u002Fpreview, when the user mentions any of these features, when replacing marker interfaces, OneOf-style results, `goto`\u002Fflag loop exits or capacity\u002Fcomparer boilerplate, or when the build reports CS8121, CS8509, CS8655, CS8510, CS0121\u002FCS0411 on a `with(...)` element, CS9370, CS9380 or CS9363.\n---\n\n# C# 15\n\nC# 15 ships with the .NET 11 SDK and Visual Studio 2026. It is the default language version for\nprojects that target `net11.0`. Its features are:\n\n| Feature | Keyword \u002F syntax | Needs preview? |\n| --- | --- | --- |\n| Collection expression arguments | `[with(args), e1, e2]` | No |\n| Union types | `union U(A, B);`, `[Union]` | No |\n| Closed hierarchies | `closed class` \u002F `closed record class` | No |\n| Extension indexers | `this[...]` inside `extension(T x) { }` | No |\n| Labeled `break` \u002F `continue` | `outer: for (...) { ... break outer; }` | No |\n| Non-virtual static interface members on older runtimes | `static` helpers in interfaces on .NET Framework \u002F netstandard | No |\n| Memory safety model | `unsafe(expr)`, `safe`, requires-unsafe `unsafe` members | **Yes** (`LangVersion=preview` + feature flag) |\n\nRead section 0 first, then the section for the feature you are using. Each section ends with the\nmistakes to avoid.\n\n---\n\n## 0. Before using any C# 15 feature\n\n1. **Check the language version.** Look at the project's `TargetFramework` and `LangVersion`.\n   `net11.0` without a `LangVersion` gives C# 15. To see the active version, temporarily add\n   `#error version`: the compiler reports CS8304 with the compiler and language versions.\n2. **Don't set `\u003CLangVersion>latest\u003C\u002FLangVersion>`.** Microsoft warns against it because it varies\n   by machine. Using a language version newer than the target framework's default is unsupported.\n   Prefer moving the TFM to `net11.0`.\n3. **Union types need runtime types.** `System.Runtime.CompilerServices.UnionAttribute` and\n   `System.Runtime.CompilerServices.IUnion` ship in the .NET 11 runtime. The compiler does **not**\n   synthesize them. When you target an older TFM, the project must reference or define them.\n4. **Know the new contextual keywords.** These can break existing identifiers, and `@` escapes them\n   (details in section 8):\n   - `with(` at the start of a collection-expression element: use `@with(...)` to call a method\n     named `with`.\n   - `union` before a type name in a declaration: use `@union`.\n   - `closed` in type declarations and modifier positions: use `@closed`.\n   - `safe`, in preview, as a member modifier: use `@safe`.\n5. **The SDK is still prerelease** (as of the October 2026 docs). The feature specs may differ from\n   the shipped compiler. The Microsoft Learn language reference describes shipped behavior, so it\n   wins when they disagree.\n\n---\n\n## 1. Collection expression arguments: `with(...)`\n\nPass arguments to the target collection's constructor or builder method from inside a collection\nexpression. The `with(...)` element must be the **first** element.\n\n```csharp\nstring[] values = [\"one\", \"two\", \"three\"];\n\nList\u003Cstring> names = [with(capacity: values.Length * 2), .. values];          \u002F\u002F List\u003CT>(int capacity)\nHashSet\u003Cstring> set = [with(StringComparer.OrdinalIgnoreCase), \"Hello\", \"HELLO\", \"hello\"]; \u002F\u002F 1 element\nIList\u003Cint> numbers = [with(capacity: 100), 1, 2, 3];                           \u002F\u002F creates List\u003Cint>(100)\nList\u003Cint> copy = [with([1, 2]), 3];                                            \u002F\u002F List\u003CT>(IEnumerable\u003CT>): 1, 2, 3\n```\n\n### How `with(...)` binds, by target type\n\n| Target type | What `with(args)` does |\n| --- | --- |\n| Class\u002Fstruct implementing `IEnumerable` (no `[CollectionBuilder]`, not a type parameter) | Overload resolution over accessible instance constructors. Named arguments and `params` (expanded form) work. |\n| Type with `[CollectionBuilder(typeof(B), \"Create\")]` | Overload resolution over `Create` overloads, treating each as if its last parameter were removed. `args` go **before** the final `ReadOnlySpan\u003CT>` parameter, which is always last. |\n| `IEnumerable\u003CT>`, `IReadOnlyCollection\u003CT>`, `IReadOnlyList\u003CT>` | Only `with()` (empty) is allowed. It means the same as no `with`. |\n| `ICollection\u003CT>`, `IList\u003CT>` | `with()` or `with(int capacity)`. The compiler constructs a `List\u003CT>`. |\n| Arrays, `Span\u003CT>`, `ReadOnlySpan\u003CT>`, anything else | **Error**, even for an empty `with()`. |\n\n### Builder types can take configuration parameters\n\nC# 15 lets `Create` methods take extra parameters before the span. A type can have several `Create`\noverloads.\n\n```csharp\n[CollectionBuilder(typeof(MySetBuilder), nameof(MySetBuilder.Create))]\npublic sealed class MySet\u003CT> : IEnumerable\u003CT>\n{\n    private readonly HashSet\u003CT> _items;\n\n    internal MySet(ReadOnlySpan\u003CT> items, IEqualityComparer\u003CT>? comparer = null)\n    {\n        _items = new HashSet\u003CT>(comparer);\n        foreach (var item in items) _items.Add(item);\n    }\n\n    public IEnumerator\u003CT> GetEnumerator() => _items.GetEnumerator();\n    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n}\n\npublic static class MySetBuilder\n{\n    public static MySet\u003CT> Create\u003CT>(ReadOnlySpan\u003CT> items) => new(items);\n    public static MySet\u003CT> Create\u003CT>(IEqualityComparer\u003CT> comparer, ReadOnlySpan\u003CT> items) => new(items, comparer);\n}\n\nMySet\u003Cstring> s = [with(StringComparer.OrdinalIgnoreCase), \"A\", \"a\", \"B\"]; \u002F\u002F two elements\nMySet\u003Cstring> t = [with(), \"x\"];                                          \u002F\u002F calls Create(ReadOnlySpan\u003CT>)\n```\n\nWhen you author a builder, put the element span **last** and the configuration parameters first.\nDon't make the span the first parameter with optional parameters after it, because `with(...)`\ncan't bind to that shape.\n\n### Types that require constructor arguments now work\n\nBefore C# 15, a collection-expression target needed a parameterless constructor. Now a type whose\nconstructors all take arguments is a valid target, but only when the expression has a `with(...)`:\n\n```csharp\npublic class NamedValues(string name) : List\u003Cint>\n{\n    public string Name { get; } = name;\n}\n\nNamedValues readings = [with(\"temperature\"), 18, 21, 24];\n\u002F\u002F NamedValues bad = [18, 21, 24];   \u002F\u002F error: no parameterless constructor and no with(...)\n```\n\n### Evaluation order\n\nThe `with(...)` arguments are evaluated first, then the elements, left to right, each exactly once.\nFor `.. GetItems()`, `GetItems()` is *called* in its left-to-right position, but *enumerating* its\nresult may happen after later elements are evaluated. Don't rely on enumeration side effects being\nordered relative to later elements.\n\n### Overload resolution and inference ignore the arguments\n\nOnly the *presence* of `with(...)` affects whether a collection expression converts to a candidate\ntype. The arguments themselves don't. They take part in resolution only after the target type is\nfixed.\n\n```csharp\nstatic void Print(List\u003Cstring> values) { }\nstatic void Print(HashSet\u003Cstring> values) { }\n\nPrint([with(StringComparer.OrdinalIgnoreCase), \"one\", \"ONE\"]); \u002F\u002F CS0121: ambiguous\nHashSet\u003Cstring> h = [with(StringComparer.OrdinalIgnoreCase), \"one\", \"ONE\"];\nPrint(h);                                                        \u002F\u002F OK\n\nstatic void Use\u003CT>(List\u003CT> values) { }\nUse([with(10)]);        \u002F\u002F CS0411: T can't be inferred from a capacity argument\nUse\u003Cint>([with(10)]);   \u002F\u002F OK\n```\n\n### Mistakes to avoid\n\n- Don't put `with(...)` anywhere but first. That's a compile error.\n- Don't pass `dynamic` arguments; that's an error. `__arglist` isn't supported either.\n- Don't use `with` on arrays or spans. Choose `List\u003CT>`, `HashSet\u003CT>` or a builder type instead.\n- `[with(default)]` on `List\u003Cint>` is ambiguous between constructors. Use named arguments\n  (`with(capacity: n)`) for clarity.\n- `IReadOnlyList\u003CT> x = [with(capacity: 10)]` is an error because read-only interfaces accept only\n  `with()`. Target `List\u003CT>` when you want to set the capacity.\n- Dictionary-interface targets (`IDictionary\u003CK,V>`, `IReadOnlyDictionary\u003CK,V>` with comparer\n  arguments) appear in the spec, but they belong to the separate *dictionary expressions* proposal,\n  which isn't in C# 15's feature list (Roslyn lists it as in progress). Don't rely on dictionary\n  expressions or `key: value` elements in C# 15 code.\n- `with(...)` is a collection-expression feature. Classic initializers\n  (`new List\u003CT>(capacity) { ... }`) are unchanged.\n- **Good refactors:** `new List\u003CT>(n)` followed by `AddRange`, and `new HashSet\u003CT>(comparer) { ... }`,\n  become `[with(n), .. src]` and `[with(comparer), a, b]`.\n\n---\n\n## 2. Union types\n\nA union value is exactly one of a fixed set of **case types**. The compiler provides implicit\nconversions from each case type, exhaustive `switch` checking and null-state tracking. C# unions\nare unions of *types*, not tagged unions. For a discriminated union, declare fresh record types as\nthe cases.\n\n```csharp\npublic record class Cat(string Name);\npublic record class Dog(string Name, string Breed);\npublic record class Bird(string Name);\n\npublic union Pet(Cat, Dog, Bird);\n\nPet pet = new Dog(\"Rex\", \"Labrador\");   \u002F\u002F implicit union conversion\n\nstring name = pet switch\n{\n    Dog d => d.Name,\n    Cat c => c.Name,\n    Bird b => b.Name,\n};                                      \u002F\u002F exhaustive: no `_` arm needed\n```\n\n### When to use a union\n\n- **Result-or-error returns** that callers must handle completely, for example\n  `union Result\u003CT>(Ok\u003CT>, Error)`.\n- **Message or command dispatch over a closed set**, where adding a case should produce warnings at\n  every `switch` that doesn't handle it yet.\n- **Replacing marker interfaces or abstract base classes** that exist only to group types for\n  pattern matching. A union needs no inheritance and no shared members.\n- **Combining types you don't own**, such as `union IntOrString(int, string)`. Inheritance can't\n  express that.\n\nUse a **closed hierarchy** (section 3) instead when the cases are your own classes, share members\nor state, or need reference semantics through a common base class.\n\n### Declaration syntax and rules\n\n```\n[attributes] [modifiers] [partial] union Name[\u003CT...>](CaseType1, CaseType2, ...) [: interfaces] [where ...]\n    { members }   or   ;\n```\n\n- **Case types** can be any type convertible to `object`: classes, structs, interfaces, type\n  parameters, nullable types and other unions. Cases may overlap.\n- **Lowering.** A union declaration lowers to a plain `struct` (not a `record struct`). The struct\n  has `[Union]`, implements `IUnion`, has a `public object? Value { get; }` and one public\n  constructor per case type. Value-type cases are **boxed** into the single `object?` field.\n- **No record behavior.** A union adds no equality members, cloning or deconstruction. It answers\n  \"which case is it?\", not \"what fields does it have?\"\n- **Body restrictions.** The body may declare methods, computed properties, operators and\n  interfaces, but **not** instance fields, auto-properties or field-like events. It also can't\n  declare a public single-parameter constructor, because those are the generated case\n  constructors. Any constructor you write must chain through `this(...)`, directly or indirectly,\n  to a generated one. A member that conflicts with a generated member is an error.\n- `union` is contextual. Escape an identifier with `@union`.\n\n```csharp\npublic record class Meters(double Value);\npublic record class Feet(double Value);\n\npublic union Length(Meters, Feet)\n{\n    \u002F\u002F Inside the body, `this switch` uses union matching on the contents.\n    public double TotalMeters => this switch\n    {\n        Meters m => m.Value,\n        Feet f => f.Value * 0.3048,\n        _ => throw new InvalidOperationException(\"The Length has no value.\"),\n    };\n\n    public Length Add(Length other) => new Meters(TotalMeters + other.TotalMeters);\n}\n\n\u002F\u002F Generic unions and \"discriminated\" style with fresh case types:\npublic sealed record class None;\npublic sealed record class Some\u003CT>(T Value);\npublic union Option\u003CT>(None, Some\u003CT>);\n\npublic sealed record class Ok\u003CT>(T Value);\npublic sealed record class Error(string Message);\npublic union Result\u003CT>(Ok\u003CT>, Error);\n\nstatic Result\u003Cint> Parse(string text)\n{\n    if (int.TryParse(text, out var number))\n        return new Ok\u003Cint>(number);   \u002F\u002F union conversion Ok\u003Cint> -> Result\u003Cint>\n    return new Error($\"'{text}' is not a number\");\n}\n```\n\n### Conversions\n\n- An implicit union conversion exists from `E` to union `U` when `E` has a *standard* implicit\n  conversion to some case type `C`. It runs the matching creation member, for example\n  `new Pet(dog)`. When `U` is a struct, `E` also converts to `U?`.\n- If more than one case type is equally applicable, the conversion is **ambiguous** (an error).\n- **A user-defined `implicit operator` beats the union conversion.** A user-defined `explicit`\n  operator wins only when you write a cast. Without a cast, the union conversion is used.\n- A union conversion isn't a standard conversion, so it doesn't chain with a user-defined\n  conversion or another union conversion.\n- There are **no explicit union conversions** and **no lifted ones**. If `int` is a case type,\n  `int?` doesn't convert to the union. Make `int?` the case type if you need that.\n\n### Pattern matching: what each pattern tests\n\nOn a union value, type-based patterns look **inside** the union. Untyped recursive patterns look at\nthe **union instance**.\n\n| Pattern on a union expression | Tests |\n| --- | --- |\n| Type or declaration pattern: `Dog`, `Dog d` | The **contents** (`Value`) |\n| Typed property\u002Fpositional pattern: `Dog { Breed: \"Lab\" }` | The contents' type, then the nested patterns on that case value |\n| Untyped property\u002Fpositional pattern: `{ Name: \"Rex\" }` | The **union instance's** own members or `Deconstruct` |\n| List pattern `[...]` | The **union instance's** count and indexer, not the contents' |\n| `var x` \u002F `_` | Captures or matches the **union instance** without unwrapping |\n| Constant\u002Frelational pattern, including `null` | The contents. `null` also matches a null class-union reference or an empty `Nullable\u003CU>`. |\n\n```csharp\npublic union Pet(Cat, Dog)\n{\n    public string Name => this switch { Cat c => c.Name, Dog d => d.Name, null => \"\" };\n}\n\nPet pet = new Cat(\"Rex\");\npet is Dog { Breed: \"Labrador\" };  \u002F\u002F false: tests the contents\npet is { Name: \"Rex\" };            \u002F\u002F true: uses the union's own Name property\npet is not null;                   \u002F\u002F true: the contents are non-null (the \"has a value\" test)\n\nPet empty = default;\nempty is { };                      \u002F\u002F TRUE: a non-nullable struct union instance always matches { }\nempty is not null;                 \u002F\u002F false: the contents are null\n```\n\n- `pet is Pet` is **error CS8121**, because `Pet` isn't one of its own case types. A type pattern\n  must be compatible with at least one case type. To test for contents, use `is not null` or\n  `.Value is not null`. To capture the union, use `var`.\n- `x is T` (the is-type operator) behaves as a type pattern on unions.\n- Logical patterns keep these distinctions. `var p and not null` captures the union and checks for\n  contents. In `Dog and { Breed: \"Lab\" }`, the type pattern passes the unwrapped `Dog` to the\n  property pattern.\n- **Avoid recursive unions** such as `union Pet(Cat, Dog, Pet)`. There, `pet is Pet` tests for a\n  *contained* `Pet`, which is easy to misread.\n- A type parameter constrained to a union type is **never** treated as a union. `u is int` on\n  `T u where T : MyUnion` is ordinary type matching.\n- Switch on the union itself (`u switch`, or `this switch` inside the body) to get union\n  exhaustiveness. Whether patterns over `.Value` (an `object?`) use the case-type knowledge is\n  still an open question in the spec, so don't rely on it.\n\n### Exhaustiveness and null: the subtle part\n\n- A `switch` *expression* that handles every case type is exhaustive, with no `_` arm needed, as\n  long as nullability analysis considers the contents non-null.\n- **Prefer a `null` arm over `_` or `var` arms.** A `_` arm silently swallows a newly added case\n  type. A `null` arm keeps the missing-case warning (CS8509) working.\n- If any case type is nullable, for example `union NullablePet(Cat?, Dog, Bird)`, the default null\n  state of `Value` is \"maybe null\". Omitting a `null` arm then gives **CS8655**.\n- **Trap:** `default(Pet)` holds **null** contents. This happens for default-initialized fields,\n  array elements and `default` itself. Yet when all case types are non-nullable, the compiler\n  tracks `Value` as \"not null\" and doesn't warn about a missing `null` arm, so the switch throws\n  `SwitchExpressionException` at run time. **Add a `null` arm whenever default union values can\n  reach the switch.**\n- Null-state rules:\n  - The default state of `Value` is \"maybe null\" if any case type is maybe-null, and \"not null\"\n    otherwise.\n  - Creating a union from a value copies that value's null state.\n  - A `true` result from `HasValue` or `TryGetValue` makes `Value` \"not null\" on that branch.\n\n```csharp\nstatic string Describe(Pet? pet) => pet switch   \u002F\u002F a nullable union struct works too\n{\n    Dog d => d.Name,\n    Cat c => c.Name,\n    Bird b => b.Name,\n    null => \"no pet\",   \u002F\u002F matches both an empty Pet? and a Pet whose Value is null\n};\n```\n\n### Custom (hand-written) union types\n\nWrite a union by hand when you need to:\n\n- adapt an existing type,\n- use a different storage strategy, such as no boxing or a tagged layout,\n- make a class-based union with reference semantics, or\n- control the layout for interop.\n\n**The basic union pattern** (all members public):\n\n1. The type has `[System.Runtime.CompilerServices.Union]`.\n2. It has one or more public constructors with exactly **one by-value or `in` parameter**. Each\n   parameter type defines a case type.\n3. It has a public `Value` property of type `object?` (or `object`) with a `get` accessor.\n\nImplementing `IUnion` (`object? Value { get; }`) is recommended. The generated unions implement it,\nand it allows runtime checks like `x is IUnion { Value: null }`.\n\n```csharp\n[System.Runtime.CompilerServices.Union]\npublic struct Shape : System.Runtime.CompilerServices.IUnion\n{\n    private readonly object? _value;\n    public Shape(Circle value) { _value = value; }\n    public Shape(Rectangle value) { _value = value; }\n    public object? Value => _value;\n}\n```\n\n**Non-boxing access pattern (optional, for performance).** Add `public bool HasValue { get; }` and\none `public bool TryGetValue(out C value)` per case type. With these, the compiler calls\n`TryGetValue` for type patterns and `HasValue` for `null` patterns instead of boxing through\n`Value`. Each member is independently optional, and neither is a fallback for the other. When a\ncase type is a nullable value type such as `int?`, the `out` parameter is the underlying `int`. The\ncompiler only picks a `TryGetValue` through identity, implicit reference or boxing conversions.\n\n```csharp\n[System.Runtime.CompilerServices.Union]\npublic struct IntOrBool : System.Runtime.CompilerServices.IUnion\n{\n    private readonly int _int; private readonly bool _bool; private readonly byte _tag; \u002F\u002F 0 none, 1 int, 2 bool\n    public IntOrBool(int? value) { if (value.HasValue) { _int = value.Value; _tag = 1; } }\n    public IntOrBool(bool? value) { if (value.HasValue) { _bool = value.Value; _tag = 2; } }\n    public object? Value => _tag switch { 1 => _int, 2 => _bool, _ => null };\n    public bool HasValue => _tag != 0;\n    public bool TryGetValue(out int value) { value = _int; return _tag == 1; }\n    public bool TryGetValue(out bool value) { value = _bool; return _tag == 2; }\n}\n\nstring s = new IntOrBool((int?)42) switch { int i => $\"int: {i}\", bool b => $\"bool: {b}\" }; \u002F\u002F no boxing\n```\n\n**Union member provider.** Use a provider when the constructors must be private, when creation\nneeds a factory, or when the type is a `record class`, a case the docs call out. Nest a **public**\ninterface named `IUnionMembers` in the union type and implement it. The compiler then looks for\nunion members **only** on that interface (inherited members included), never on the type itself.\nThe interface declares:\n\n- a static `Create(C value)` method per case type, whose return type is identity-convertible to the\n  union,\n- `Value`,\n- optionally `TryGetValue` and `HasValue`.\n\n```csharp\n[System.Runtime.CompilerServices.Union]\npublic struct Outcome\u003CT> : Outcome\u003CT>.IUnionMembers\n{\n    private readonly object? _value;\n    private Outcome(object? value) => _value = value;\n\n    public interface IUnionMembers\n    {\n        static Outcome\u003CT> Create(T? value) => new(value);\n        static Outcome\u003CT> Create(Exception? value) => new(value);\n        object? Value { get; }\n        bool TryGetValue(out T value);\n        bool TryGetValue(out Exception value);\n    }\n\n    object? IUnionMembers.Value => _value;\n    public bool TryGetValue(out T value) { if (_value is T t) { value = t; return true; } value = default!; return false; }\n    public bool TryGetValue(out Exception value) { if (_value is Exception e) { value = e; return true; } value = default!; return false; }\n}\n```\n\n**Class-based unions** work the same way: put `[Union]` on a class. There, `null` matches both a\nnull reference and a null `Value`. Seal class-based unions. Per the spec discussion, a derived\nclass picks up `IUnion` but gets its own constructor set, which produces confusing union matching.\n\n**Well-formedness contract.** The compiler trusts these rules without checking them, so a type\nthat breaks them gets wrong matching behavior:\n\n- **Soundness:** `Value` is always null or an instance of a case type, even for `default`.\n- **Stability:** a union created from case `C` reports `C`, or null if the input was null.\n- **Creation equivalence:** if a value converts to two case types, both constructors behave the\n  same for it.\n- **Consistency:** `HasValue` and `TryGetValue` agree with `Value`.\n\n### Mistakes to avoid\n\n- Don't add instance fields or auto-properties to a `union` body. Put data in the case types.\n- Don't use `_ => ...` to \"be safe\". Use `null => ...` so that new cases still warn.\n- Don't assume generated unions are allocation-free: value-type cases box. On hot paths, hand-write\n  a union with the non-boxing pattern.\n- Don't write `x is MyUnion` to test whether a union holds something. Use `is not null`.\n- Don't confuse `{ }` with \"has a value\". On a struct union, `{ }` always matches.\n- Don't nest unions or list a union as its own case unless you're sure you need it.\n- Union struct functions that read `this` more than once can see torn updates when a variable is\n  reassigned concurrently. If that matters, copy `this` into a local first.\n\n---\n\n## 3. Closed hierarchies: `closed`\n\n`closed` on a class means only its **declaring assembly (and module)** may declare **direct**\nsubclasses. Because the set of direct descendants is fixed, a `switch` expression that handles them\nall is exhaustive without a default arm, including in consuming assemblies.\n\n```csharp\n\u002F\u002F Assembly 1\npublic closed record class JobStatus;\npublic record class Queued : JobStatus;\npublic record class Running(int PercentComplete) : JobStatus;\npublic record class Completed(TimeSpan Elapsed) : JobStatus;\npublic sealed record class Failed(string Error) : JobStatus;\n\n\u002F\u002F Any assembly\npublic static string Describe(JobStatus status) => status switch\n{\n    Queued => \"waiting to start\",\n    Running(var percent) => $\"{percent}% complete\",\n    Completed(var elapsed) => $\"finished in {elapsed.TotalSeconds:F1}s\",\n    Failed(var error) => $\"failed: {error}\",\n};  \u002F\u002F no CS8509\n\n\u002F\u002F Assembly 2\npublic record class Paused : JobStatus;   \u002F\u002F error: 'JobStatus' is a closed class\n```\n\n### Declaration rules\n\n- `closed` applies **only to classes**, including record classes, not to structs or interfaces.\n- A closed class is **implicitly `abstract`**, so you can't instantiate it. Combining `closed` with\n  `sealed`, `static` or an explicit `abstract` is an error.\n- Direct subtypes must be declared in the same assembly **and module** as the closed class.\n- **It isn't transitive.** A plain subclass of a closed class can be extended from other\n  assemblies. Mark the leaves `sealed`, or the intermediate levels `closed`, to lock them down.\n- **Generic rule:** a generic class that directly derives from a closed class must use **every**\n  one of its type parameters in the base class specification.\n\n```csharp\npublic closed record class Tree\u003CT>;\npublic record class Leaf\u003CT>(T Value) : Tree\u003CT>;                        \u002F\u002F OK\npublic record class Branch\u003CT>(Tree\u003CT> Left, Tree\u003CT> Right) : Tree\u003CT>;  \u002F\u002F OK\npublic record class Constant\u003CU>(U Value) : Tree\u003Cint>;                  \u002F\u002F error: U not used in the base\n```\n\n- `closed` is contextual. A type named `closed` now needs `@closed` (CS9380), and a field of type\n  `closed` may now parse as a modifier (CS1519).\n\n### Exhaustiveness rules\n\n- **Only direct descendants count.** Indirect descendants are covered by their parent's arm.\n  Ordinary subsumption still applies: put a more-derived arm (`Sedan`) **before** its base (`Car`).\n  The reverse order gives CS8510 (unreachable).\n- An arm for the closed base type after all direct descendants is an **unreachable-case error**.\n- **Accessibility matters.** If a direct descendant isn't accessible at the switch site (for\n  example, an `internal` subtype seen from another assembly, or a `protected` nested subtype), the\n  switch isn't exhaustive (CS8509). Fix this with a `_` arm, a base-type arm, or by making every\n  direct subtype at least as accessible as the base.\n- **Nullable input:** a switch over `JobStatus?` also needs a `null` arm.\n- **Type parameters:** a switch over `X` where `X : JobStatus` is exhaustive on the same terms as a\n  switch over `JobStatus`.\n- **Generic closed bases:** only subtypes that can actually produce the given construction are\n  required. For `C\u003Cstring>`, a `D2\u003CV> : C\u003CV[]>` case isn't needed. Constraints on subtypes\n  **aren't** used to rule cases out, and a non-speakable generic subtype makes the switch\n  non-exhaustive. Add a base-type arm in those situations.\n- A closed class with **no** subtypes isn't exhausted by an empty switch.\n- Exhaustiveness applies to `switch` *expressions*, which is where the missing-case diagnostic\n  comes from.\n\n### Other effects\n\n- **Sealed hierarchy interface checks.** When every class in a closed hierarchy is `sealed` or\n  `closed`, an explicit cast to an interface that no class in the hierarchy implements is a compile\n  error, the same rule as for a sealed class.\n- **Metadata.** The class gets `[IsClosedType]`, and every constructor gets\n  `[CompilerFeatureRequired(\"ClosedClasses\")]`. Older compilers and VB therefore can't derive from\n  it.\n- **Versioning.** Adding `closed` to a published class, or adding a new direct subtype to a closed\n  class, is a **breaking change** for consumers, whose exhaustive switches stop being exhaustive.\n  Treat the subtype list as public API.\n\n### Union or closed hierarchy?\n\n| Choose a union when | Choose a closed hierarchy when |\n| --- | --- |\n| The cases are existing or unrelated types (`int`, `string`, third-party types) | You own every case type and they form one family |\n| You don't want inheritance or shared members | The cases share base members, state or virtual behavior |\n| A lightweight struct wrapper suits you (watch boxing) | You want reference semantics and polymorphism |\n| The same type might belong to several unions | A type belongs to exactly one family |\n\n---\n\n## 4. Extension indexers\n\nC# 14 extension blocks can now declare **indexers**. Indexers are instance members, so the block\nneeds a **named receiver**.\n\n```csharp\npublic static class SequenceIndexer\n{\n    extension(IEnumerable\u003Cint> sequence)\n    {\n        public int this[int index] => sequence.ElementAt(index);\n    }\n}\n\nIEnumerable\u003Cint> numbers = Enumerable.Range(1, 10);\nint third = numbers[2];\n\npublic static class SettingsExtensions\n{\n    extension(IDictionary\u003Cstring, string> settings)\n    {\n        public string this[string section, string key]          \u002F\u002F get + set\n        {\n            get => settings[$\"{section}:{key}\"];\n            set => settings[$\"{section}:{key}\"] = value;\n        }\n    }\n}\nsettings[\"Logging\", \"Level\"] = \"Debug\";\n```\n\n### Rules\n\n- Extension indexers support everything ordinary indexers do: `get` and `set`, expression bodies,\n  `ref`-returning accessors, `scoped` parameters, attributes and `params`.\n- **Not allowed:** `abstract`, `virtual`, `override`, `new`, `sealed`, `partial`, `protected` and\n  related modifiers, and `init` accessors. These are the existing extension-member restrictions.\n- Every type parameter of a generic extension block must appear in the receiver or the indexer's\n  parameters.\n- `[IndexerName(\"X\")]` changes the metadata names: an `X` property and `get_X`\u002F`set_X`\n  implementation methods, `Item` by default. The implementation methods are static methods on the\n  enclosing class with the receiver first, so you can disambiguate with\n  `SettingsExtensions.get_Item(settings, \"Logging\", \"Level\")`.\n- **Lookup order** (the first applicable tier wins):\n  1. real instance indexers,\n  2. implicit `Index`\u002F`Range` support from instance members,\n  3. extension indexers,\n  4. implicit `Index`\u002F`Range` support from extension members.\n\n  An extension can never hijack an existing instance indexer.\n- Within each scope, lookup tries `Length` before `Count`, starting with instance members and then\n  moving outward through extension scopes.\n- **Type inference** uses only the receiver and the index arguments, never the assigned value.\n  `i[42, null] = new object();` fails inference where calling `E.set_Item(...)` would succeed.\n- Null-conditional element access (`x?[i]`), index assignments in object initializers, list patterns\n  and spread patterns all use the same resolution.\n\n### Unlock `^`, ranges and list patterns with extensions\n\nAn extension `Count` or `Length`, an extension `this[int]` and a `Slice(int, int)` make a type\nindexable from the end, sliceable and matchable with list patterns. Classic `this`-parameter\nextension methods count too.\n\n```csharp\npublic sealed class Readings(int[] values) { public int[] Values { get; } = values; }\n\npublic static class ReadingExtensions\n{\n    extension(Readings readings)\n    {\n        public int Count => readings.Values.Length;\n        public int this[int index] => readings.Values[index];\n        public Readings Slice(int start, int length) => new(readings.Values.AsSpan(start, length).ToArray());\n    }\n}\n\nReadings r = new([10, 20, 30, 40]);\n_ = r[^1];               \u002F\u002F 40\n_ = r[1..3][0];          \u002F\u002F 20\n_ = r is [10, .., 40];   \u002F\u002F true\n```\n\n### Limitations\n\n- Extension indexers are **never used for arrays or `string`**, even if you declare one.\n- They can't appear in **expression trees**. This matters for LINQ providers such as EF Core:\n  don't use extension indexers inside `IQueryable` lambdas.\n- They aren't considered on `base[...]` access, or when the receiver is a type rather than a value.\n- Extension `Length` and `Count` don't feed the collection-expression spread optimization, so\n  `[.. x]` won't presize from them.\n\n---\n\n## 5. Labeled `break` and `continue`\n\nPut a label directly on a loop or `switch` statement, then name it from an inner statement.\n\n```csharp\nouter: for (int row = 0; row \u003C grid.Height; row++)\n{\n    for (int column = 0; column \u003C grid.Width; column++)\n    {\n        if (grid[row, column].IsBlocked) continue outer;   \u002F\u002F next row\n        if (grid[row, column].IsGoal)    break outer;      \u002F\u002F leave both loops\n    }\n}\n\ndispatch: switch (command.Kind)\n{\n    case CommandKind.Batch:\n        foreach (var step in command.Steps)\n        {\n            if (step.IsAbort) break dispatch;   \u002F\u002F exits the switch statement, not just the foreach\n            Run(step);\n        }\n        break;\n    default:\n        Run(command);\n        break;\n}\n```\n\n### Rules\n\n- `break label;` targets the nearest enclosing `for`, `foreach`, `while`, `do` or `switch`\n  **statement** with that label. A `switch` *expression* isn't a target.\n- `continue label;` targets only a **loop**. It can't target a `switch`.\n- Only the statement **immediately** after the label is labeled. In `a: b: while (...)`, the loop is\n  labeled `b`, so `break a;` doesn't target it. Use one label per loop.\n- Unlabeled `break` and `continue` behave exactly as before.\n- Neither form can leave a `finally` block. If the jump crosses `try` blocks, their `finally`\n  blocks run in order, innermost first.\n- As with unlabeled jumps, the target must enclose the statement **in the same function**. You\n  can't jump out of a lambda or local function to an outer loop.\n- Labels share `goto`'s label rules. A label's scope is its whole block, including nested blocks,\n  and two labels with the same name and overlapping scopes are an error. **Give each labeled loop\n  in a method a distinct name**, such as `rows:` and `cols:`, rather than reusing `outer:`.\n- The same label can serve both `break` and `continue`, which removes the old pair of `goto`\n  labels at the end of the body and after the loop.\n\n### Refactoring guidance\n\n- Replace a Boolean \"found\" flag that's re-checked at each level with `break label;`.\n- Replace `goto END;` placed right after a loop with `break label;`.\n- Replace `goto NEXT;` with `NEXT: ;` at the end of the body with `continue label;`.\n- The **IDE0410** analyzer (\"Use labeled jump statement\") flags these patterns and offers fixes. Its\n  option is `csharp_style_prefer_labeled_jump_statements = true|false` (default `true`). Disable it\n  with `dotnet_diagnostic.IDE0410.severity = none`.\n- Extracting a method is still often cleaner. Use labeled jumps when the loops share many locals or\n  extraction would need tuples or `out` parameters.\n\n---\n\n## 6. Non-virtual static interface members on older runtimes\n\nC# 15 lets you declare and call **non-virtual static** interface members even when the target\nruntime doesn't support default interface implementations, as on .NET Framework or\n`netstandard2.0`. This helps multi-targeted libraries.\n\n```csharp\npublic interface IMeasurement\n{\n    public static double ToMeters(double centimeters) => centimeters \u002F 100;\n}\n\ndouble m = IMeasurement.ToMeters(250);   \u002F\u002F call it on the interface, not on an implementing type\n```\n\nThese still require runtime support for default interface methods:\n\n- instance default implementations,\n- `static abstract` and `static virtual` members,\n- `protected`, `protected internal` and `private protected` interface members.\n\nFor down-level targets, keep interface helpers static and non-virtual, and don't give them the\n`protected` access modifiers.\n\n---\n\n## 7. Memory safety model (preview)\n\nThis is the first step of a multi-release redesign. `unsafe` moves from marking code that\n*mentions pointers* to marking code that *accesses unmanaged memory*. An `unsafe` member becomes a\ncontract that **its callers** must uphold. **Only use this when the user opts in.** It requires\npreview settings.\n\n### Enabling it (two independent switches)\n\n```xml\n\u003CPropertyGroup>\n  \u003CLangVersion>preview\u003C\u002FLangVersion>                                \u003C!-- syntax + pointer relaxations -->\n  \u003CFeatures>$(Features);updated-memory-safety-rules\u003C\u002FFeatures>       \u003C!-- the new rules (requires-unsafe) -->\n  \u003CAllowUnsafeBlocks>true\u003C\u002FAllowUnsafeBlocks>                       \u003C!-- needed to write unsafe\u002Fsafe\u002Funsafe(...) -->\n\u003C\u002FPropertyGroup>\n```\n\nIn a file-based app:\n\n```csharp\n#:property LangVersion=preview\n#:property Features=$(Features);updated-memory-safety-rules\n```\n\n- `AllowUnsafeBlocks` is independent of the other two. A project with the updated rules but without\n  `AllowUnsafeBlocks` simply gets errors when it calls requires-unsafe APIs.\n- A future stable `\u003CMemorySafetyRules>` property is planned but **not implemented**. Don't use it.\n- Some docs and diagnostics call this language version \"C# 16\" (`langversion:16`), meaning the\n  preview version that follows C# 15.\n\n### What needs an `unsafe` context\n\n| Operation | Original model | Preview model |\n| --- | --- | --- |\n| Declare a pointer type, take `&x` | unsafe | **safe** |\n| `fixed` statement | unsafe | **safe** |\n| `stackalloc` converted to a pointer | unsafe | **safe** |\n| `sizeof(T)` for any unmanaged `T` | unsafe | **safe** |\n| `*p`, `p->m`, `p[i]` | unsafe | unsafe |\n| Function pointer invocation | unsafe | unsafe |\n| Fixed-size buffer element access | unsafe | unsafe |\n| Calling a member marked `unsafe` | no caller requirement | **caller needs unsafe** (with the updated rules) |\n| `stackalloc` to `Span\u003CT>` without an initializer in a `[SkipLocalsInit]` member | safe | **unsafe** (with the updated rules) |\n\nThe relaxations (the first four rows) apply with `LangVersion=preview` even when the assembly\nhasn't opted in to the updated rules.\n\n### Requires-unsafe members (with the updated rules)\n\n- `unsafe` on a member's signature makes it **requires-unsafe**: every caller must be in an\n  `unsafe` context. It no longer creates an unsafe context for the body, so wrap the dereference\n  in an inner `unsafe { }` block.\n\n```csharp\npublic static unsafe int ReadInt32(byte* source)   \u002F\u002F obligation flows to callers\n{\n    unsafe { return *(int*)source; }               \u002F\u002F unsafe operation scoped inside\n}\n\nunsafe { int v = ReadInt32(buffer); }              \u002F\u002F the caller takes on the audit\n```\n\n- **Propagate or discharge.** A member either marks itself `unsafe` (propagate), or validates its\n  inputs, uses an inner `unsafe` block and keeps a safe signature (discharge). A discharging member\n  is an *unsafe boundary*.\n\n```csharp\npublic static int SumBytes(byte[] source)          \u002F\u002F safe signature\n{\n    ArgumentNullException.ThrowIfNull(source);\n    fixed (byte* first = source)                   \u002F\u002F no unsafe needed to pin\n    {\n        unsafe\n        {\n            \u002F\u002F SAFETY: the null check and source.Length bound every read to the pinned array.\n            int total = 0;\n            for (int i = 0; i \u003C source.Length; i++) total += first[i];\n            return total;\n        }\n    }\n}\n```\n\n- **Document contracts.** Put a `\u002F\u002F\u002F \u003Csafety>...\u003C\u002Fsafety>` block on each requires-unsafe member\n  describing what callers must guarantee, which an analyzer can require. Put a `\u002F\u002F SAFETY:` comment\n  inside each `unsafe` block explaining why that spot is sound.\n- **Errors under the updated rules:**\n  - `unsafe` on a type declaration, a static constructor, a finalizer, a `delegate` or a lambda.\n  - Adding `unsafe` to an override or implementation of a member that isn't requires-unsafe.\n  - Converting a requires-unsafe method to a delegate outside an unsafe context.\n- An `unsafe` constructor gets an unsafe context in its `: base(...)`\u002F`: this(...)` initializer.\n- A type whose parameterless constructor is `unsafe` doesn't satisfy a `new()` or `struct`\n  constraint in declarations such as base types, field types and aliases (CS9376). In expressions,\n  it satisfies them only inside an `unsafe` context.\n- Local functions and lambdas don't inherit `unsafe` or `safe` from the containing member. Mark a\n  local function `unsafe` explicitly. Lambdas can't be `unsafe`.\n- Both parts of a `partial` member must agree on `unsafe`\u002F`safe`.\n- **Properties:** put `unsafe`\u002F`safe` on the property *or* on individual accessors, not both, and\n  not the same modifier on every accessor. Event accessors can't be marked individually.\n- **Fields:** an `unsafe` field forces every write into an `unsafe` context. Use it when the field's\n  type can't express an invariant, such as a `byte*` plus a length. `readonly unsafe` adds a\n  write-once guarantee. Marking a property or event `unsafe` doesn't affect its backing field.\n\n### The `safe` keyword\n\n`safe` attests that a declaration is sound. Ordinary declarations are safe by default, so use it\nonly where the compiler requires a choice:\n\n- every **`extern`** method, including `LibraryImport` partials,\n- every instance field of a type with `LayoutKind.Explicit`, `[ExtendedLayout]`, or a nonzero\n  `Pack`\u002F`Size`.\n\nFor a backing field, annotate the auto-property or field-like event instead. Static and const\nfields are exempt.\n\n```csharp\n[LibraryImport(\"libc\")]\ninternal static safe partial int getpid();                 \u002F\u002F no pointers: attest safe\n\n[LibraryImport(\"libc\", StringMarshalling = StringMarshalling.Utf8)]\ninternal static unsafe partial nint strlen(byte* str);      \u002F\u002F dereferences a pointer: propagate\n```\n\n`safe` and `unsafe` can't both appear on one declaration. There's no `safe { }` block. Newer\ncompilers (after .NET 11.0.100) require `AllowUnsafeBlocks` for both declaration modifiers and\nreport CS9401 without it.\n\n### `unsafe(expression)`\n\n`unsafe(expression)` creates an unsafe context for exactly one expression, ending at the closing\nparenthesis. Use it where a block can't go, or to keep the unsafe scope minimal:\n\n```csharp\nstatic readonly int Signature = unsafe(ReadSignature());       \u002F\u002F field initializer\nreturn await unsafe(ReadSignatureCoreAsync());                 \u002F\u002F only the call is unsafe, not the await\nint b = unsafe(c[null]);                                       \u002F\u002F indexer with a pointer parameter (CS9363 otherwise)\n```\n\nIt also works in constructor initializers and `catch (...) when (...)` filters. It requires\n`AllowUnsafeBlocks` and the preview language version.\n\n### Async and other details\n\n- `await` is now allowed inside `unsafe` blocks, but **not inside a `fixed` statement**. Pointers\n  kept alive across an `await` are your responsibility.\n- **Cross-assembly behavior.** An opted-in assembly gets `[module: MemorySafetyRules(...)]`, and its\n  requires-unsafe members get `[RequiresUnsafe]`. You can't apply either attribute yourself.\n\n| Caller | Callee | Result |\n| --- | --- | --- |\n| Updated rules | Updated rules | `unsafe` markers flow through metadata. Calls need an unsafe context. |\n| Updated rules | Original rules | Compat mode: any callee member with a pointer or function pointer in its signature is treated as requires-unsafe. |\n| Original rules | Updated rules | The original pointer rules apply. A requires-unsafe member with no pointer in its signature is callable from safe code. |\n\n### Breaking changes when moving to the preview version\n\n- Lambdas can now bind to delegates with pointer parameters, so overloads can become ambiguous\n  (CS0121). Fix this with explicit lambda parameter types: `M((int x) => { })`.\n- `safe` becomes a modifier, so a type named `safe` needs `@safe`.\n- Indexers and members with pointer parameters now need `unsafe` at the call site (CS9363).\n\n---\n\n## 8. Other compiler breaking changes in the .NET 11 SDK\n\nWatch for these when you upgrade:\n\n- `[with(x, y), z]` is now collection arguments, not a call to a method named `with`, at\n  LangVersion 15 or later. Use `@with(x, y)` to call the method.\n- `union Foo;` inside a type can now parse as a union declaration (CS9370). Use `@union`.\n- A type named `closed` needs `@closed` (CS9380), and fields of that type may produce CS1519.\n- A `Span\u003CT>`\u002F`ReadOnlySpan\u003CT>` collection expression now has *declaration-block* safe-context.\n  Assigning a loop-local `Span\u003Cint> items = [x];` to an outer `scoped` span is now an error. Use an\n  array, or hoist the span out of the loop.\n- `nameof(this.P)` inside an attribute is now an error. Write `nameof(P)`.\n- `(X.Y) when` in a switch-expression arm now parses as the constant pattern `(X.Y)` followed by a\n  `when` clause, not as a cast.\n- `x && y`, where `x` is statically an interface type and `y` is `dynamic`, is now error CS7083.\n  Cast `x` to a concrete type or to `dynamic`.\n- Synthesized `ref readonly`-returning delegates and `ref readonly` local functions now need\n  `System.Runtime.InteropServices.InAttribute` (CS0518 if it's missing).\n\n---\n\n## 9. Agent checklist\n\n- [ ] Confirm the project is on C# 15 (`net11.0`, or an explicit `LangVersion` of 15). Don't add\n      `latest`.\n- [ ] Use `[with(...), ...]` instead of construct-then-add boilerplate when a capacity, comparer or\n      constructor argument matters. Never use it with arrays or spans.\n- [ ] Model \"one of these types\" with `union`. Model \"one of my subclasses\" with `closed`. Switch\n      on the union or the closed base, not on `.Value` or `object`.\n- [ ] In exhaustive switches, prefer explicit `null` arms over `_`, and always handle `null` when\n      default union values or nullable inputs can arrive.\n- [ ] Seal the leaves of closed hierarchies, and treat their subtype lists as public API.\n- [ ] Hand-write a union with `TryGetValue`\u002F`HasValue` for value-type cases on hot paths.\n- [ ] Give each labeled loop a unique label in the method. `continue` never targets a `switch`.\n- [ ] Don't use extension indexers on arrays or strings, or inside expression trees and\n      `IQueryable` queries.\n- [ ] Touch the memory-safety preview only when the user has opted in. Keep `unsafe` blocks\n      minimal, and document every requires-unsafe member with `\u002F\u002F\u002F \u003Csafety>`.\n\n## Diagnostic quick reference\n\n| Diagnostic | Meaning in C# 15 context |\n| --- | --- |\n| CS8121 | A type pattern isn't compatible with any union case type (for example `pet is Pet`). |\n| CS8509 | Switch not exhaustive: a missing union case, or an inaccessible closed-hierarchy subtype. |\n| CS8655 | Union contents are maybe-null and there's no `null` arm. |\n| CS8510 | Unreachable arm (a base arm after its subtypes, or `Car` before `Sedan`). |\n| CS0121 \u002F CS0411 | `with(...)` arguments don't pick overloads or infer type arguments. |\n| CS9370 \u002F CS9380 \u002F CS1519 | `union`\u002F`closed` used as an identifier. Escape it with `@`. |\n| CS9363 | A member with pointer parameters (for example an indexer) called outside `unsafe` (preview). |\n| CS9376 | A requires-unsafe parameterless constructor used where `new()`\u002F`struct` is required (preview). |\n| CS9392 | An explicit-layout field needs `safe`\u002F`unsafe` (preview). |\n| CS9401 \u002F CS0227 | `safe`\u002F`unsafe` modifiers or blocks used without `AllowUnsafeBlocks`. |\n| `SwitchExpressionException` | Run time: a `default` union (null contents) reached a switch with no `null` arm. |\n\n## Sources\n\n- What's new in C# 15: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Fwhats-new\u002Fcsharp-15\n- Collection expressions (arguments): https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Foperators\u002Fcollection-expressions#collection-expression-arguments\n- Spec, collection expression arguments: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Fcsharp-15.0\u002Fcollection-expression-arguments\n- Union types: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fbuiltin-types\u002Funion\n- Spec, unions: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Fcsharp-15.0\u002Funions\n- `closed` modifier: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fkeywords\u002Fclosed\n- Patterns (closed hierarchy and union patterns): https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Foperators\u002Fpatterns\n- Spec, closed hierarchies: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Fcsharp-15.0\u002Fclosed-hierarchies\n- Extension members (indexers): https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fkeywords\u002Fextension#extension-indexers\n- Spec, extension indexers: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Fcsharp-15.0\u002Fextension-indexers\n- Jump statements: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fstatements\u002Fjump-statements\n- Spec, labeled break\u002Fcontinue: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Fcsharp-15.0\u002Flabeled-break-continue\n- IDE0410: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Ffundamentals\u002Fcode-analysis\u002Fstyle-rules\u002Fide0410\n- Interface static members and runtime support: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fkeywords\u002Finterface#static-interface-members-and-runtime-support\n- Unsafe code (updated memory safety model): https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Funsafe-code\n- Spec, memory safety: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Funsafe-evolution\n- Compiler options (enabling the memory safety rules): https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fcompiler-options\u002Flanguage#enable-the-updated-memory-safety-rules\n- Compiler breaking changes in .NET 11: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Fwhats-new\u002Fbreaking-changes\u002Fcompiler%20breaking%20changes%20-%20dotnet%2011\n- Roslyn language feature status: https:\u002F\u002Fgithub.com\u002Fdotnet\u002Froslyn\u002Fblob\u002Fmain\u002Fdocs\u002FLanguage%20Feature%20Status.md\n","# C# 15\n\nC# 15 ships with the .NET 11 SDK and Visual Studio 2026. It is the default language version for\nprojects that target `net11.0`. Its features are:\n\n| Feature | Keyword \u002F syntax | Needs preview? |\n| --- | --- | --- |\n| Collection expression arguments | `[with(args), e1, e2]` | No |\n| Union types | `union U(A, B);`, `[Union]` | No |\n| Closed hierarchies | `closed class` \u002F `closed record class` | No |\n| Extension indexers | `this[...]` inside `extension(T x) { }` | No |\n| Labeled `break` \u002F `continue` | `outer: for (...) { ... break outer; }` | No |\n| Non-virtual static interface members on older runtimes | `static` helpers in interfaces on .NET Framework \u002F netstandard | No |\n| Memory safety model | `unsafe(expr)`, `safe`, requires-unsafe `unsafe` members | **Yes** (`LangVersion=preview` + feature flag) |\n\nRead section 0 first, then the section for the feature you are using. Each section ends with the\nmistakes to avoid.\n\n---\n\n## 0. Before using any C# 15 feature\n\n1. **Check the language version.** Look at the project's `TargetFramework` and `LangVersion`.\n   `net11.0` without a `LangVersion` gives C# 15. To see the active version, temporarily add\n   `#error version`: the compiler reports CS8304 with the compiler and language versions.\n2. **Don't set `\u003CLangVersion>latest\u003C\u002FLangVersion>`.** Microsoft warns against it because it varies\n   by machine. Using a language version newer than the target framework's default is unsupported.\n   Prefer moving the TFM to `net11.0`.\n3. **Union types need runtime types.** `System.Runtime.CompilerServices.UnionAttribute` and\n   `System.Runtime.CompilerServices.IUnion` ship in the .NET 11 runtime. The compiler does **not**\n   synthesize them. When you target an older TFM, the project must reference or define them.\n4. **Know the new contextual keywords.** These can break existing identifiers, and `@` escapes them\n   (details in section 8):\n   - `with(` at the start of a collection-expression element: use `@with(...)` to call a method\n     named `with`.\n   - `union` before a type name in a declaration: use `@union`.\n   - `closed` in type declarations and modifier positions: use `@closed`.\n   - `safe`, in preview, as a member modifier: use `@safe`.\n5. **The SDK is still prerelease** (as of the October 2026 docs). The feature specs may differ from\n   the shipped compiler. The Microsoft Learn language reference describes shipped behavior, so it\n   wins when they disagree.\n\n---\n\n## 1. Collection expression arguments: `with(...)`\n\nPass arguments to the target collection's constructor or builder method from inside a collection\nexpression. The `with(...)` element must be the **first** element.\n\n```csharp\nstring[] values = [\"one\", \"two\", \"three\"];\n\nList\u003Cstring> names = [with(capacity: values.Length * 2), .. values];          \u002F\u002F List\u003CT>(int capacity)\nHashSet\u003Cstring> set = [with(StringComparer.OrdinalIgnoreCase), \"Hello\", \"HELLO\", \"hello\"]; \u002F\u002F 1 element\nIList\u003Cint> numbers = [with(capacity: 100), 1, 2, 3];                           \u002F\u002F creates List\u003Cint>(100)\nList\u003Cint> copy = [with([1, 2]), 3];                                            \u002F\u002F List\u003CT>(IEnumerable\u003CT>): 1, 2, 3\n```\n\n### How `with(...)` binds, by target type\n\n| Target type | What `with(args)` does |\n| --- | --- |\n| Class\u002Fstruct implementing `IEnumerable` (no `[CollectionBuilder]`, not a type parameter) | Overload resolution over accessible instance constructors. Named arguments and `params` (expanded form) work. |\n| Type with `[CollectionBuilder(typeof(B), \"Create\")]` | Overload resolution over `Create` overloads, treating each as if its last parameter were removed. `args` go **before** the final `ReadOnlySpan\u003CT>` parameter, which is always last. |\n| `IEnumerable\u003CT>`, `IReadOnlyCollection\u003CT>`, `IReadOnlyList\u003CT>` | Only `with()` (empty) is allowed. It means the same as no `with`. |\n| `ICollection\u003CT>`, `IList\u003CT>` | `with()` or `with(int capacity)`. The compiler constructs a `List\u003CT>`. |\n| Arrays, `Span\u003CT>`, `ReadOnlySpan\u003CT>`, anything else | **Error**, even for an empty `with()`. |\n\n### Builder types can take configuration parameters\n\nC# 15 lets `Create` methods take extra parameters before the span. A type can have several `Create`\noverloads.\n\n```csharp\n[CollectionBuilder(typeof(MySetBuilder), nameof(MySetBuilder.Create))]\npublic sealed class MySet\u003CT> : IEnumerable\u003CT>\n{\n    private readonly HashSet\u003CT> _items;\n\n    internal MySet(ReadOnlySpan\u003CT> items, IEqualityComparer\u003CT>? comparer = null)\n    {\n        _items = new HashSet\u003CT>(comparer);\n        foreach (var item in items) _items.Add(item);\n    }\n\n    public IEnumerator\u003CT> GetEnumerator() => _items.GetEnumerator();\n    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n}\n\npublic static class MySetBuilder\n{\n    public static MySet\u003CT> Create\u003CT>(ReadOnlySpan\u003CT> items) => new(items);\n    public static MySet\u003CT> Create\u003CT>(IEqualityComparer\u003CT> comparer, ReadOnlySpan\u003CT> items) => new(items, comparer);\n}\n\nMySet\u003Cstring> s = [with(StringComparer.OrdinalIgnoreCase), \"A\", \"a\", \"B\"]; \u002F\u002F two elements\nMySet\u003Cstring> t = [with(), \"x\"];                                          \u002F\u002F calls Create(ReadOnlySpan\u003CT>)\n```\n\nWhen you author a builder, put the element span **last** and the configuration parameters first.\nDon't make the span the first parameter with optional parameters after it, because `with(...)`\ncan't bind to that shape.\n\n### Types that require constructor arguments now work\n\nBefore C# 15, a collection-expression target needed a parameterless constructor. Now a type whose\nconstructors all take arguments is a valid target, but only when the expression has a `with(...)`:\n\n```csharp\npublic class NamedValues(string name) : List\u003Cint>\n{\n    public string Name { get; } = name;\n}\n\nNamedValues readings = [with(\"temperature\"), 18, 21, 24];\n\u002F\u002F NamedValues bad = [18, 21, 24];   \u002F\u002F error: no parameterless constructor and no with(...)\n```\n\n### Evaluation order\n\nThe `with(...)` arguments are evaluated first, then the elements, left to right, each exactly once.\nFor `.. GetItems()`, `GetItems()` is *called* in its left-to-right position, but *enumerating* its\nresult may happen after later elements are evaluated. Don't rely on enumeration side effects being\nordered relative to later elements.\n\n### Overload resolution and inference ignore the arguments\n\nOnly the *presence* of `with(...)` affects whether a collection expression converts to a candidate\ntype. The arguments themselves don't. They take part in resolution only after the target type is\nfixed.\n\n```csharp\nstatic void Print(List\u003Cstring> values) { }\nstatic void Print(HashSet\u003Cstring> values) { }\n\nPrint([with(StringComparer.OrdinalIgnoreCase), \"one\", \"ONE\"]); \u002F\u002F CS0121: ambiguous\nHashSet\u003Cstring> h = [with(StringComparer.OrdinalIgnoreCase), \"one\", \"ONE\"];\nPrint(h);                                                        \u002F\u002F OK\n\nstatic void Use\u003CT>(List\u003CT> values) { }\nUse([with(10)]);        \u002F\u002F CS0411: T can't be inferred from a capacity argument\nUse\u003Cint>([with(10)]);   \u002F\u002F OK\n```\n\n### Mistakes to avoid\n\n- Don't put `with(...)` anywhere but first. That's a compile error.\n- Don't pass `dynamic` arguments; that's an error. `__arglist` isn't supported either.\n- Don't use `with` on arrays or spans. Choose `List\u003CT>`, `HashSet\u003CT>` or a builder type instead.\n- `[with(default)]` on `List\u003Cint>` is ambiguous between constructors. Use named arguments\n  (`with(capacity: n)`) for clarity.\n- `IReadOnlyList\u003CT> x = [with(capacity: 10)]` is an error because read-only interfaces accept only\n  `with()`. Target `List\u003CT>` when you want to set the capacity.\n- Dictionary-interface targets (`IDictionary\u003CK,V>`, `IReadOnlyDictionary\u003CK,V>` with comparer\n  arguments) appear in the spec, but they belong to the separate *dictionary expressions* proposal,\n  which isn't in C# 15's feature list (Roslyn lists it as in progress). Don't rely on dictionary\n  expressions or `key: value` elements in C# 15 code.\n- `with(...)` is a collection-expression feature. Classic initializers\n  (`new List\u003CT>(capacity) { ... }`) are unchanged.\n- **Good refactors:** `new List\u003CT>(n)` followed by `AddRange`, and `new HashSet\u003CT>(comparer) { ... }`,\n  become `[with(n), .. src]` and `[with(comparer), a, b]`.\n\n---\n\n## 2. Union types\n\nA union value is exactly one of a fixed set of **case types**. The compiler provides implicit\nconversions from each case type, exhaustive `switch` checking and null-state tracking. C# unions\nare unions of *types*, not tagged unions. For a discriminated union, declare fresh record types as\nthe cases.\n\n```csharp\npublic record class Cat(string Name);\npublic record class Dog(string Name, string Breed);\npublic record class Bird(string Name);\n\npublic union Pet(Cat, Dog, Bird);\n\nPet pet = new Dog(\"Rex\", \"Labrador\");   \u002F\u002F implicit union conversion\n\nstring name = pet switch\n{\n    Dog d => d.Name,\n    Cat c => c.Name,\n    Bird b => b.Name,\n};                                      \u002F\u002F exhaustive: no `_` arm needed\n```\n\n### When to use a union\n\n- **Result-or-error returns** that callers must handle completely, for example\n  `union Result\u003CT>(Ok\u003CT>, Error)`.\n- **Message or command dispatch over a closed set**, where adding a case should produce warnings at\n  every `switch` that doesn't handle it yet.\n- **Replacing marker interfaces or abstract base classes** that exist only to group types for\n  pattern matching. A union needs no inheritance and no shared members.\n- **Combining types you don't own**, such as `union IntOrString(int, string)`. Inheritance can't\n  express that.\n\nUse a **closed hierarchy** (section 3) instead when the cases are your own classes, share members\nor state, or need reference semantics through a common base class.\n\n### Declaration syntax and rules\n\n```\n[attributes] [modifiers] [partial] union Name[\u003CT...>](CaseType1, CaseType2, ...) [: interfaces] [where ...]\n    { members }   or   ;\n```\n\n- **Case types** can be any type convertible to `object`: classes, structs, interfaces, type\n  parameters, nullable types and other unions. Cases may overlap.\n- **Lowering.** A union declaration lowers to a plain `struct` (not a `record struct`). The struct\n  has `[Union]`, implements `IUnion`, has a `public object? Value { get; }` and one public\n  constructor per case type. Value-type cases are **boxed** into the single `object?` field.\n- **No record behavior.** A union adds no equality members, cloning or deconstruction. It answers\n  \"which case is it?\", not \"what fields does it have?\"\n- **Body restrictions.** The body may declare methods, computed properties, operators and\n  interfaces, but **not** instance fields, auto-properties or field-like events. It also can't\n  declare a public single-parameter constructor, because those are the generated case\n  constructors. Any constructor you write must chain through `this(...)`, directly or indirectly,\n  to a generated one. A member that conflicts with a generated member is an error.\n- `union` is contextual. Escape an identifier with `@union`.\n\n```csharp\npublic record class Meters(double Value);\npublic record class Feet(double Value);\n\npublic union Length(Meters, Feet)\n{\n    \u002F\u002F Inside the body, `this switch` uses union matching on the contents.\n    public double TotalMeters => this switch\n    {\n        Meters m => m.Value,\n        Feet f => f.Value * 0.3048,\n        _ => throw new InvalidOperationException(\"The Length has no value.\"),\n    };\n\n    public Length Add(Length other) => new Meters(TotalMeters + other.TotalMeters);\n}\n\n\u002F\u002F Generic unions and \"discriminated\" style with fresh case types:\npublic sealed record class None;\npublic sealed record class Some\u003CT>(T Value);\npublic union Option\u003CT>(None, Some\u003CT>);\n\npublic sealed record class Ok\u003CT>(T Value);\npublic sealed record class Error(string Message);\npublic union Result\u003CT>(Ok\u003CT>, Error);\n\nstatic Result\u003Cint> Parse(string text)\n{\n    if (int.TryParse(text, out var number))\n        return new Ok\u003Cint>(number);   \u002F\u002F union conversion Ok\u003Cint> -> Result\u003Cint>\n    return new Error($\"'{text}' is not a number\");\n}\n```\n\n### Conversions\n\n- An implicit union conversion exists from `E` to union `U` when `E` has a *standard* implicit\n  conversion to some case type `C`. It runs the matching creation member, for example\n  `new Pet(dog)`. When `U` is a struct, `E` also converts to `U?`.\n- If more than one case type is equally applicable, the conversion is **ambiguous** (an error).\n- **A user-defined `implicit operator` beats the union conversion.** A user-defined `explicit`\n  operator wins only when you write a cast. Without a cast, the union conversion is used.\n- A union conversion isn't a standard conversion, so it doesn't chain with a user-defined\n  conversion or another union conversion.\n- There are **no explicit union conversions** and **no lifted ones**. If `int` is a case type,\n  `int?` doesn't convert to the union. Make `int?` the case type if you need that.\n\n### Pattern matching: what each pattern tests\n\nOn a union value, type-based patterns look **inside** the union. Untyped recursive patterns look at\nthe **union instance**.\n\n| Pattern on a union expression | Tests |\n| --- | --- |\n| Type or declaration pattern: `Dog`, `Dog d` | The **contents** (`Value`) |\n| Typed property\u002Fpositional pattern: `Dog { Breed: \"Lab\" }` | The contents' type, then the nested patterns on that case value |\n| Untyped property\u002Fpositional pattern: `{ Name: \"Rex\" }` | The **union instance's** own members or `Deconstruct` |\n| List pattern `[...]` | The **union instance's** count and indexer, not the contents' |\n| `var x` \u002F `_` | Captures or matches the **union instance** without unwrapping |\n| Constant\u002Frelational pattern, including `null` | The contents. `null` also matches a null class-union reference or an empty `Nullable\u003CU>`. |\n\n```csharp\npublic union Pet(Cat, Dog)\n{\n    public string Name => this switch { Cat c => c.Name, Dog d => d.Name, null => \"\" };\n}\n\nPet pet = new Cat(\"Rex\");\npet is Dog { Breed: \"Labrador\" };  \u002F\u002F false: tests the contents\npet is { Name: \"Rex\" };            \u002F\u002F true: uses the union's own Name property\npet is not null;                   \u002F\u002F true: the contents are non-null (the \"has a value\" test)\n\nPet empty = default;\nempty is { };                      \u002F\u002F TRUE: a non-nullable struct union instance always matches { }\nempty is not null;                 \u002F\u002F false: the contents are null\n```\n\n- `pet is Pet` is **error CS8121**, because `Pet` isn't one of its own case types. A type pattern\n  must be compatible with at least one case type. To test for contents, use `is not null` or\n  `.Value is not null`. To capture the union, use `var`.\n- `x is T` (the is-type operator) behaves as a type pattern on unions.\n- Logical patterns keep these distinctions. `var p and not null` captures the union and checks for\n  contents. In `Dog and { Breed: \"Lab\" }`, the type pattern passes the unwrapped `Dog` to the\n  property pattern.\n- **Avoid recursive unions** such as `union Pet(Cat, Dog, Pet)`. There, `pet is Pet` tests for a\n  *contained* `Pet`, which is easy to misread.\n- A type parameter constrained to a union type is **never** treated as a union. `u is int` on\n  `T u where T : MyUnion` is ordinary type matching.\n- Switch on the union itself (`u switch`, or `this switch` inside the body) to get union\n  exhaustiveness. Whether patterns over `.Value` (an `object?`) use the case-type knowledge is\n  still an open question in the spec, so don't rely on it.\n\n### Exhaustiveness and null: the subtle part\n\n- A `switch` *expression* that handles every case type is exhaustive, with no `_` arm needed, as\n  long as nullability analysis considers the contents non-null.\n- **Prefer a `null` arm over `_` or `var` arms.** A `_` arm silently swallows a newly added case\n  type. A `null` arm keeps the missing-case warning (CS8509) working.\n- If any case type is nullable, for example `union NullablePet(Cat?, Dog, Bird)`, the default null\n  state of `Value` is \"maybe null\". Omitting a `null` arm then gives **CS8655**.\n- **Trap:** `default(Pet)` holds **null** contents. This happens for default-initialized fields,\n  array elements and `default` itself. Yet when all case types are non-nullable, the compiler\n  tracks `Value` as \"not null\" and doesn't warn about a missing `null` arm, so the switch throws\n  `SwitchExpressionException` at run time. **Add a `null` arm whenever default union values can\n  reach the switch.**\n- Null-state rules:\n  - The default state of `Value` is \"maybe null\" if any case type is maybe-null, and \"not null\"\n    otherwise.\n  - Creating a union from a value copies that value's null state.\n  - A `true` result from `HasValue` or `TryGetValue` makes `Value` \"not null\" on that branch.\n\n```csharp\nstatic string Describe(Pet? pet) => pet switch   \u002F\u002F a nullable union struct works too\n{\n    Dog d => d.Name,\n    Cat c => c.Name,\n    Bird b => b.Name,\n    null => \"no pet\",   \u002F\u002F matches both an empty Pet? and a Pet whose Value is null\n};\n```\n\n### Custom (hand-written) union types\n\nWrite a union by hand when you need to:\n\n- adapt an existing type,\n- use a different storage strategy, such as no boxing or a tagged layout,\n- make a class-based union with reference semantics, or\n- control the layout for interop.\n\n**The basic union pattern** (all members public):\n\n1. The type has `[System.Runtime.CompilerServices.Union]`.\n2. It has one or more public constructors with exactly **one by-value or `in` parameter**. Each\n   parameter type defines a case type.\n3. It has a public `Value` property of type `object?` (or `object`) with a `get` accessor.\n\nImplementing `IUnion` (`object? Value { get; }`) is recommended. The generated unions implement it,\nand it allows runtime checks like `x is IUnion { Value: null }`.\n\n```csharp\n[System.Runtime.CompilerServices.Union]\npublic struct Shape : System.Runtime.CompilerServices.IUnion\n{\n    private readonly object? _value;\n    public Shape(Circle value) { _value = value; }\n    public Shape(Rectangle value) { _value = value; }\n    public object? Value => _value;\n}\n```\n\n**Non-boxing access pattern (optional, for performance).** Add `public bool HasValue { get; }` and\none `public bool TryGetValue(out C value)` per case type. With these, the compiler calls\n`TryGetValue` for type patterns and `HasValue` for `null` patterns instead of boxing through\n`Value`. Each member is independently optional, and neither is a fallback for the other. When a\ncase type is a nullable value type such as `int?`, the `out` parameter is the underlying `int`. The\ncompiler only picks a `TryGetValue` through identity, implicit reference or boxing conversions.\n\n```csharp\n[System.Runtime.CompilerServices.Union]\npublic struct IntOrBool : System.Runtime.CompilerServices.IUnion\n{\n    private readonly int _int; private readonly bool _bool; private readonly byte _tag; \u002F\u002F 0 none, 1 int, 2 bool\n    public IntOrBool(int? value) { if (value.HasValue) { _int = value.Value; _tag = 1; } }\n    public IntOrBool(bool? value) { if (value.HasValue) { _bool = value.Value; _tag = 2; } }\n    public object? Value => _tag switch { 1 => _int, 2 => _bool, _ => null };\n    public bool HasValue => _tag != 0;\n    public bool TryGetValue(out int value) { value = _int; return _tag == 1; }\n    public bool TryGetValue(out bool value) { value = _bool; return _tag == 2; }\n}\n\nstring s = new IntOrBool((int?)42) switch { int i => $\"int: {i}\", bool b => $\"bool: {b}\" }; \u002F\u002F no boxing\n```\n\n**Union member provider.** Use a provider when the constructors must be private, when creation\nneeds a factory, or when the type is a `record class`, a case the docs call out. Nest a **public**\ninterface named `IUnionMembers` in the union type and implement it. The compiler then looks for\nunion members **only** on that interface (inherited members included), never on the type itself.\nThe interface declares:\n\n- a static `Create(C value)` method per case type, whose return type is identity-convertible to the\n  union,\n- `Value`,\n- optionally `TryGetValue` and `HasValue`.\n\n```csharp\n[System.Runtime.CompilerServices.Union]\npublic struct Outcome\u003CT> : Outcome\u003CT>.IUnionMembers\n{\n    private readonly object? _value;\n    private Outcome(object? value) => _value = value;\n\n    public interface IUnionMembers\n    {\n        static Outcome\u003CT> Create(T? value) => new(value);\n        static Outcome\u003CT> Create(Exception? value) => new(value);\n        object? Value { get; }\n        bool TryGetValue(out T value);\n        bool TryGetValue(out Exception value);\n    }\n\n    object? IUnionMembers.Value => _value;\n    public bool TryGetValue(out T value) { if (_value is T t) { value = t; return true; } value = default!; return false; }\n    public bool TryGetValue(out Exception value) { if (_value is Exception e) { value = e; return true; } value = default!; return false; }\n}\n```\n\n**Class-based unions** work the same way: put `[Union]` on a class. There, `null` matches both a\nnull reference and a null `Value`. Seal class-based unions. Per the spec discussion, a derived\nclass picks up `IUnion` but gets its own constructor set, which produces confusing union matching.\n\n**Well-formedness contract.** The compiler trusts these rules without checking them, so a type\nthat breaks them gets wrong matching behavior:\n\n- **Soundness:** `Value` is always null or an instance of a case type, even for `default`.\n- **Stability:** a union created from case `C` reports `C`, or null if the input was null.\n- **Creation equivalence:** if a value converts to two case types, both constructors behave the\n  same for it.\n- **Consistency:** `HasValue` and `TryGetValue` agree with `Value`.\n\n### Mistakes to avoid\n\n- Don't add instance fields or auto-properties to a `union` body. Put data in the case types.\n- Don't use `_ => ...` to \"be safe\". Use `null => ...` so that new cases still warn.\n- Don't assume generated unions are allocation-free: value-type cases box. On hot paths, hand-write\n  a union with the non-boxing pattern.\n- Don't write `x is MyUnion` to test whether a union holds something. Use `is not null`.\n- Don't confuse `{ }` with \"has a value\". On a struct union, `{ }` always matches.\n- Don't nest unions or list a union as its own case unless you're sure you need it.\n- Union struct functions that read `this` more than once can see torn updates when a variable is\n  reassigned concurrently. If that matters, copy `this` into a local first.\n\n---\n\n## 3. Closed hierarchies: `closed`\n\n`closed` on a class means only its **declaring assembly (and module)** may declare **direct**\nsubclasses. Because the set of direct descendants is fixed, a `switch` expression that handles them\nall is exhaustive without a default arm, including in consuming assemblies.\n\n```csharp\n\u002F\u002F Assembly 1\npublic closed record class JobStatus;\npublic record class Queued : JobStatus;\npublic record class Running(int PercentComplete) : JobStatus;\npublic record class Completed(TimeSpan Elapsed) : JobStatus;\npublic sealed record class Failed(string Error) : JobStatus;\n\n\u002F\u002F Any assembly\npublic static string Describe(JobStatus status) => status switch\n{\n    Queued => \"waiting to start\",\n    Running(var percent) => $\"{percent}% complete\",\n    Completed(var elapsed) => $\"finished in {elapsed.TotalSeconds:F1}s\",\n    Failed(var error) => $\"failed: {error}\",\n};  \u002F\u002F no CS8509\n\n\u002F\u002F Assembly 2\npublic record class Paused : JobStatus;   \u002F\u002F error: 'JobStatus' is a closed class\n```\n\n### Declaration rules\n\n- `closed` applies **only to classes**, including record classes, not to structs or interfaces.\n- A closed class is **implicitly `abstract`**, so you can't instantiate it. Combining `closed` with\n  `sealed`, `static` or an explicit `abstract` is an error.\n- Direct subtypes must be declared in the same assembly **and module** as the closed class.\n- **It isn't transitive.** A plain subclass of a closed class can be extended from other\n  assemblies. Mark the leaves `sealed`, or the intermediate levels `closed`, to lock them down.\n- **Generic rule:** a generic class that directly derives from a closed class must use **every**\n  one of its type parameters in the base class specification.\n\n```csharp\npublic closed record class Tree\u003CT>;\npublic record class Leaf\u003CT>(T Value) : Tree\u003CT>;                        \u002F\u002F OK\npublic record class Branch\u003CT>(Tree\u003CT> Left, Tree\u003CT> Right) : Tree\u003CT>;  \u002F\u002F OK\npublic record class Constant\u003CU>(U Value) : Tree\u003Cint>;                  \u002F\u002F error: U not used in the base\n```\n\n- `closed` is contextual. A type named `closed` now needs `@closed` (CS9380), and a field of type\n  `closed` may now parse as a modifier (CS1519).\n\n### Exhaustiveness rules\n\n- **Only direct descendants count.** Indirect descendants are covered by their parent's arm.\n  Ordinary subsumption still applies: put a more-derived arm (`Sedan`) **before** its base (`Car`).\n  The reverse order gives CS8510 (unreachable).\n- An arm for the closed base type after all direct descendants is an **unreachable-case error**.\n- **Accessibility matters.** If a direct descendant isn't accessible at the switch site (for\n  example, an `internal` subtype seen from another assembly, or a `protected` nested subtype), the\n  switch isn't exhaustive (CS8509). Fix this with a `_` arm, a base-type arm, or by making every\n  direct subtype at least as accessible as the base.\n- **Nullable input:** a switch over `JobStatus?` also needs a `null` arm.\n- **Type parameters:** a switch over `X` where `X : JobStatus` is exhaustive on the same terms as a\n  switch over `JobStatus`.\n- **Generic closed bases:** only subtypes that can actually produce the given construction are\n  required. For `C\u003Cstring>`, a `D2\u003CV> : C\u003CV[]>` case isn't needed. Constraints on subtypes\n  **aren't** used to rule cases out, and a non-speakable generic subtype makes the switch\n  non-exhaustive. Add a base-type arm in those situations.\n- A closed class with **no** subtypes isn't exhausted by an empty switch.\n- Exhaustiveness applies to `switch` *expressions*, which is where the missing-case diagnostic\n  comes from.\n\n### Other effects\n\n- **Sealed hierarchy interface checks.** When every class in a closed hierarchy is `sealed` or\n  `closed`, an explicit cast to an interface that no class in the hierarchy implements is a compile\n  error, the same rule as for a sealed class.\n- **Metadata.** The class gets `[IsClosedType]`, and every constructor gets\n  `[CompilerFeatureRequired(\"ClosedClasses\")]`. Older compilers and VB therefore can't derive from\n  it.\n- **Versioning.** Adding `closed` to a published class, or adding a new direct subtype to a closed\n  class, is a **breaking change** for consumers, whose exhaustive switches stop being exhaustive.\n  Treat the subtype list as public API.\n\n### Union or closed hierarchy?\n\n| Choose a union when | Choose a closed hierarchy when |\n| --- | --- |\n| The cases are existing or unrelated types (`int`, `string`, third-party types) | You own every case type and they form one family |\n| You don't want inheritance or shared members | The cases share base members, state or virtual behavior |\n| A lightweight struct wrapper suits you (watch boxing) | You want reference semantics and polymorphism |\n| The same type might belong to several unions | A type belongs to exactly one family |\n\n---\n\n## 4. Extension indexers\n\nC# 14 extension blocks can now declare **indexers**. Indexers are instance members, so the block\nneeds a **named receiver**.\n\n```csharp\npublic static class SequenceIndexer\n{\n    extension(IEnumerable\u003Cint> sequence)\n    {\n        public int this[int index] => sequence.ElementAt(index);\n    }\n}\n\nIEnumerable\u003Cint> numbers = Enumerable.Range(1, 10);\nint third = numbers[2];\n\npublic static class SettingsExtensions\n{\n    extension(IDictionary\u003Cstring, string> settings)\n    {\n        public string this[string section, string key]          \u002F\u002F get + set\n        {\n            get => settings[$\"{section}:{key}\"];\n            set => settings[$\"{section}:{key}\"] = value;\n        }\n    }\n}\nsettings[\"Logging\", \"Level\"] = \"Debug\";\n```\n\n### Rules\n\n- Extension indexers support everything ordinary indexers do: `get` and `set`, expression bodies,\n  `ref`-returning accessors, `scoped` parameters, attributes and `params`.\n- **Not allowed:** `abstract`, `virtual`, `override`, `new`, `sealed`, `partial`, `protected` and\n  related modifiers, and `init` accessors. These are the existing extension-member restrictions.\n- Every type parameter of a generic extension block must appear in the receiver or the indexer's\n  parameters.\n- `[IndexerName(\"X\")]` changes the metadata names: an `X` property and `get_X`\u002F`set_X`\n  implementation methods, `Item` by default. The implementation methods are static methods on the\n  enclosing class with the receiver first, so you can disambiguate with\n  `SettingsExtensions.get_Item(settings, \"Logging\", \"Level\")`.\n- **Lookup order** (the first applicable tier wins):\n  1. real instance indexers,\n  2. implicit `Index`\u002F`Range` support from instance members,\n  3. extension indexers,\n  4. implicit `Index`\u002F`Range` support from extension members.\n\n  An extension can never hijack an existing instance indexer.\n- Within each scope, lookup tries `Length` before `Count`, starting with instance members and then\n  moving outward through extension scopes.\n- **Type inference** uses only the receiver and the index arguments, never the assigned value.\n  `i[42, null] = new object();` fails inference where calling `E.set_Item(...)` would succeed.\n- Null-conditional element access (`x?[i]`), index assignments in object initializers, list patterns\n  and spread patterns all use the same resolution.\n\n### Unlock `^`, ranges and list patterns with extensions\n\nAn extension `Count` or `Length`, an extension `this[int]` and a `Slice(int, int)` make a type\nindexable from the end, sliceable and matchable with list patterns. Classic `this`-parameter\nextension methods count too.\n\n```csharp\npublic sealed class Readings(int[] values) { public int[] Values { get; } = values; }\n\npublic static class ReadingExtensions\n{\n    extension(Readings readings)\n    {\n        public int Count => readings.Values.Length;\n        public int this[int index] => readings.Values[index];\n        public Readings Slice(int start, int length) => new(readings.Values.AsSpan(start, length).ToArray());\n    }\n}\n\nReadings r = new([10, 20, 30, 40]);\n_ = r[^1];               \u002F\u002F 40\n_ = r[1..3][0];          \u002F\u002F 20\n_ = r is [10, .., 40];   \u002F\u002F true\n```\n\n### Limitations\n\n- Extension indexers are **never used for arrays or `string`**, even if you declare one.\n- They can't appear in **expression trees**. This matters for LINQ providers such as EF Core:\n  don't use extension indexers inside `IQueryable` lambdas.\n- They aren't considered on `base[...]` access, or when the receiver is a type rather than a value.\n- Extension `Length` and `Count` don't feed the collection-expression spread optimization, so\n  `[.. x]` won't presize from them.\n\n---\n\n## 5. Labeled `break` and `continue`\n\nPut a label directly on a loop or `switch` statement, then name it from an inner statement.\n\n```csharp\nouter: for (int row = 0; row \u003C grid.Height; row++)\n{\n    for (int column = 0; column \u003C grid.Width; column++)\n    {\n        if (grid[row, column].IsBlocked) continue outer;   \u002F\u002F next row\n        if (grid[row, column].IsGoal)    break outer;      \u002F\u002F leave both loops\n    }\n}\n\ndispatch: switch (command.Kind)\n{\n    case CommandKind.Batch:\n        foreach (var step in command.Steps)\n        {\n            if (step.IsAbort) break dispatch;   \u002F\u002F exits the switch statement, not just the foreach\n            Run(step);\n        }\n        break;\n    default:\n        Run(command);\n        break;\n}\n```\n\n### Rules\n\n- `break label;` targets the nearest enclosing `for`, `foreach`, `while`, `do` or `switch`\n  **statement** with that label. A `switch` *expression* isn't a target.\n- `continue label;` targets only a **loop**. It can't target a `switch`.\n- Only the statement **immediately** after the label is labeled. In `a: b: while (...)`, the loop is\n  labeled `b`, so `break a;` doesn't target it. Use one label per loop.\n- Unlabeled `break` and `continue` behave exactly as before.\n- Neither form can leave a `finally` block. If the jump crosses `try` blocks, their `finally`\n  blocks run in order, innermost first.\n- As with unlabeled jumps, the target must enclose the statement **in the same function**. You\n  can't jump out of a lambda or local function to an outer loop.\n- Labels share `goto`'s label rules. A label's scope is its whole block, including nested blocks,\n  and two labels with the same name and overlapping scopes are an error. **Give each labeled loop\n  in a method a distinct name**, such as `rows:` and `cols:`, rather than reusing `outer:`.\n- The same label can serve both `break` and `continue`, which removes the old pair of `goto`\n  labels at the end of the body and after the loop.\n\n### Refactoring guidance\n\n- Replace a Boolean \"found\" flag that's re-checked at each level with `break label;`.\n- Replace `goto END;` placed right after a loop with `break label;`.\n- Replace `goto NEXT;` with `NEXT: ;` at the end of the body with `continue label;`.\n- The **IDE0410** analyzer (\"Use labeled jump statement\") flags these patterns and offers fixes. Its\n  option is `csharp_style_prefer_labeled_jump_statements = true|false` (default `true`). Disable it\n  with `dotnet_diagnostic.IDE0410.severity = none`.\n- Extracting a method is still often cleaner. Use labeled jumps when the loops share many locals or\n  extraction would need tuples or `out` parameters.\n\n---\n\n## 6. Non-virtual static interface members on older runtimes\n\nC# 15 lets you declare and call **non-virtual static** interface members even when the target\nruntime doesn't support default interface implementations, as on .NET Framework or\n`netstandard2.0`. This helps multi-targeted libraries.\n\n```csharp\npublic interface IMeasurement\n{\n    public static double ToMeters(double centimeters) => centimeters \u002F 100;\n}\n\ndouble m = IMeasurement.ToMeters(250);   \u002F\u002F call it on the interface, not on an implementing type\n```\n\nThese still require runtime support for default interface methods:\n\n- instance default implementations,\n- `static abstract` and `static virtual` members,\n- `protected`, `protected internal` and `private protected` interface members.\n\nFor down-level targets, keep interface helpers static and non-virtual, and don't give them the\n`protected` access modifiers.\n\n---\n\n## 7. Memory safety model (preview)\n\nThis is the first step of a multi-release redesign. `unsafe` moves from marking code that\n*mentions pointers* to marking code that *accesses unmanaged memory*. An `unsafe` member becomes a\ncontract that **its callers** must uphold. **Only use this when the user opts in.** It requires\npreview settings.\n\n### Enabling it (two independent switches)\n\n```xml\n\u003CPropertyGroup>\n  \u003CLangVersion>preview\u003C\u002FLangVersion>                                \u003C!-- syntax + pointer relaxations -->\n  \u003CFeatures>$(Features);updated-memory-safety-rules\u003C\u002FFeatures>       \u003C!-- the new rules (requires-unsafe) -->\n  \u003CAllowUnsafeBlocks>true\u003C\u002FAllowUnsafeBlocks>                       \u003C!-- needed to write unsafe\u002Fsafe\u002Funsafe(...) -->\n\u003C\u002FPropertyGroup>\n```\n\nIn a file-based app:\n\n```csharp\n#:property LangVersion=preview\n#:property Features=$(Features);updated-memory-safety-rules\n```\n\n- `AllowUnsafeBlocks` is independent of the other two. A project with the updated rules but without\n  `AllowUnsafeBlocks` simply gets errors when it calls requires-unsafe APIs.\n- A future stable `\u003CMemorySafetyRules>` property is planned but **not implemented**. Don't use it.\n- Some docs and diagnostics call this language version \"C# 16\" (`langversion:16`), meaning the\n  preview version that follows C# 15.\n\n### What needs an `unsafe` context\n\n| Operation | Original model | Preview model |\n| --- | --- | --- |\n| Declare a pointer type, take `&x` | unsafe | **safe** |\n| `fixed` statement | unsafe | **safe** |\n| `stackalloc` converted to a pointer | unsafe | **safe** |\n| `sizeof(T)` for any unmanaged `T` | unsafe | **safe** |\n| `*p`, `p->m`, `p[i]` | unsafe | unsafe |\n| Function pointer invocation | unsafe | unsafe |\n| Fixed-size buffer element access | unsafe | unsafe |\n| Calling a member marked `unsafe` | no caller requirement | **caller needs unsafe** (with the updated rules) |\n| `stackalloc` to `Span\u003CT>` without an initializer in a `[SkipLocalsInit]` member | safe | **unsafe** (with the updated rules) |\n\nThe relaxations (the first four rows) apply with `LangVersion=preview` even when the assembly\nhasn't opted in to the updated rules.\n\n### Requires-unsafe members (with the updated rules)\n\n- `unsafe` on a member's signature makes it **requires-unsafe**: every caller must be in an\n  `unsafe` context. It no longer creates an unsafe context for the body, so wrap the dereference\n  in an inner `unsafe { }` block.\n\n```csharp\npublic static unsafe int ReadInt32(byte* source)   \u002F\u002F obligation flows to callers\n{\n    unsafe { return *(int*)source; }               \u002F\u002F unsafe operation scoped inside\n}\n\nunsafe { int v = ReadInt32(buffer); }              \u002F\u002F the caller takes on the audit\n```\n\n- **Propagate or discharge.** A member either marks itself `unsafe` (propagate), or validates its\n  inputs, uses an inner `unsafe` block and keeps a safe signature (discharge). A discharging member\n  is an *unsafe boundary*.\n\n```csharp\npublic static int SumBytes(byte[] source)          \u002F\u002F safe signature\n{\n    ArgumentNullException.ThrowIfNull(source);\n    fixed (byte* first = source)                   \u002F\u002F no unsafe needed to pin\n    {\n        unsafe\n        {\n            \u002F\u002F SAFETY: the null check and source.Length bound every read to the pinned array.\n            int total = 0;\n            for (int i = 0; i \u003C source.Length; i++) total += first[i];\n            return total;\n        }\n    }\n}\n```\n\n- **Document contracts.** Put a `\u002F\u002F\u002F \u003Csafety>...\u003C\u002Fsafety>` block on each requires-unsafe member\n  describing what callers must guarantee, which an analyzer can require. Put a `\u002F\u002F SAFETY:` comment\n  inside each `unsafe` block explaining why that spot is sound.\n- **Errors under the updated rules:**\n  - `unsafe` on a type declaration, a static constructor, a finalizer, a `delegate` or a lambda.\n  - Adding `unsafe` to an override or implementation of a member that isn't requires-unsafe.\n  - Converting a requires-unsafe method to a delegate outside an unsafe context.\n- An `unsafe` constructor gets an unsafe context in its `: base(...)`\u002F`: this(...)` initializer.\n- A type whose parameterless constructor is `unsafe` doesn't satisfy a `new()` or `struct`\n  constraint in declarations such as base types, field types and aliases (CS9376). In expressions,\n  it satisfies them only inside an `unsafe` context.\n- Local functions and lambdas don't inherit `unsafe` or `safe` from the containing member. Mark a\n  local function `unsafe` explicitly. Lambdas can't be `unsafe`.\n- Both parts of a `partial` member must agree on `unsafe`\u002F`safe`.\n- **Properties:** put `unsafe`\u002F`safe` on the property *or* on individual accessors, not both, and\n  not the same modifier on every accessor. Event accessors can't be marked individually.\n- **Fields:** an `unsafe` field forces every write into an `unsafe` context. Use it when the field's\n  type can't express an invariant, such as a `byte*` plus a length. `readonly unsafe` adds a\n  write-once guarantee. Marking a property or event `unsafe` doesn't affect its backing field.\n\n### The `safe` keyword\n\n`safe` attests that a declaration is sound. Ordinary declarations are safe by default, so use it\nonly where the compiler requires a choice:\n\n- every **`extern`** method, including `LibraryImport` partials,\n- every instance field of a type with `LayoutKind.Explicit`, `[ExtendedLayout]`, or a nonzero\n  `Pack`\u002F`Size`.\n\nFor a backing field, annotate the auto-property or field-like event instead. Static and const\nfields are exempt.\n\n```csharp\n[LibraryImport(\"libc\")]\ninternal static safe partial int getpid();                 \u002F\u002F no pointers: attest safe\n\n[LibraryImport(\"libc\", StringMarshalling = StringMarshalling.Utf8)]\ninternal static unsafe partial nint strlen(byte* str);      \u002F\u002F dereferences a pointer: propagate\n```\n\n`safe` and `unsafe` can't both appear on one declaration. There's no `safe { }` block. Newer\ncompilers (after .NET 11.0.100) require `AllowUnsafeBlocks` for both declaration modifiers and\nreport CS9401 without it.\n\n### `unsafe(expression)`\n\n`unsafe(expression)` creates an unsafe context for exactly one expression, ending at the closing\nparenthesis. Use it where a block can't go, or to keep the unsafe scope minimal:\n\n```csharp\nstatic readonly int Signature = unsafe(ReadSignature());       \u002F\u002F field initializer\nreturn await unsafe(ReadSignatureCoreAsync());                 \u002F\u002F only the call is unsafe, not the await\nint b = unsafe(c[null]);                                       \u002F\u002F indexer with a pointer parameter (CS9363 otherwise)\n```\n\nIt also works in constructor initializers and `catch (...) when (...)` filters. It requires\n`AllowUnsafeBlocks` and the preview language version.\n\n### Async and other details\n\n- `await` is now allowed inside `unsafe` blocks, but **not inside a `fixed` statement**. Pointers\n  kept alive across an `await` are your responsibility.\n- **Cross-assembly behavior.** An opted-in assembly gets `[module: MemorySafetyRules(...)]`, and its\n  requires-unsafe members get `[RequiresUnsafe]`. You can't apply either attribute yourself.\n\n| Caller | Callee | Result |\n| --- | --- | --- |\n| Updated rules | Updated rules | `unsafe` markers flow through metadata. Calls need an unsafe context. |\n| Updated rules | Original rules | Compat mode: any callee member with a pointer or function pointer in its signature is treated as requires-unsafe. |\n| Original rules | Updated rules | The original pointer rules apply. A requires-unsafe member with no pointer in its signature is callable from safe code. |\n\n### Breaking changes when moving to the preview version\n\n- Lambdas can now bind to delegates with pointer parameters, so overloads can become ambiguous\n  (CS0121). Fix this with explicit lambda parameter types: `M((int x) => { })`.\n- `safe` becomes a modifier, so a type named `safe` needs `@safe`.\n- Indexers and members with pointer parameters now need `unsafe` at the call site (CS9363).\n\n---\n\n## 8. Other compiler breaking changes in the .NET 11 SDK\n\nWatch for these when you upgrade:\n\n- `[with(x, y), z]` is now collection arguments, not a call to a method named `with`, at\n  LangVersion 15 or later. Use `@with(x, y)` to call the method.\n- `union Foo;` inside a type can now parse as a union declaration (CS9370). Use `@union`.\n- A type named `closed` needs `@closed` (CS9380), and fields of that type may produce CS1519.\n- A `Span\u003CT>`\u002F`ReadOnlySpan\u003CT>` collection expression now has *declaration-block* safe-context.\n  Assigning a loop-local `Span\u003Cint> items = [x];` to an outer `scoped` span is now an error. Use an\n  array, or hoist the span out of the loop.\n- `nameof(this.P)` inside an attribute is now an error. Write `nameof(P)`.\n- `(X.Y) when` in a switch-expression arm now parses as the constant pattern `(X.Y)` followed by a\n  `when` clause, not as a cast.\n- `x && y`, where `x` is statically an interface type and `y` is `dynamic`, is now error CS7083.\n  Cast `x` to a concrete type or to `dynamic`.\n- Synthesized `ref readonly`-returning delegates and `ref readonly` local functions now need\n  `System.Runtime.InteropServices.InAttribute` (CS0518 if it's missing).\n\n---\n\n## 9. Agent checklist\n\n- [ ] Confirm the project is on C# 15 (`net11.0`, or an explicit `LangVersion` of 15). Don't add\n      `latest`.\n- [ ] Use `[with(...), ...]` instead of construct-then-add boilerplate when a capacity, comparer or\n      constructor argument matters. Never use it with arrays or spans.\n- [ ] Model \"one of these types\" with `union`. Model \"one of my subclasses\" with `closed`. Switch\n      on the union or the closed base, not on `.Value` or `object`.\n- [ ] In exhaustive switches, prefer explicit `null` arms over `_`, and always handle `null` when\n      default union values or nullable inputs can arrive.\n- [ ] Seal the leaves of closed hierarchies, and treat their subtype lists as public API.\n- [ ] Hand-write a union with `TryGetValue`\u002F`HasValue` for value-type cases on hot paths.\n- [ ] Give each labeled loop a unique label in the method. `continue` never targets a `switch`.\n- [ ] Don't use extension indexers on arrays or strings, or inside expression trees and\n      `IQueryable` queries.\n- [ ] Touch the memory-safety preview only when the user has opted in. Keep `unsafe` blocks\n      minimal, and document every requires-unsafe member with `\u002F\u002F\u002F \u003Csafety>`.\n\n## Diagnostic quick reference\n\n| Diagnostic | Meaning in C# 15 context |\n| --- | --- |\n| CS8121 | A type pattern isn't compatible with any union case type (for example `pet is Pet`). |\n| CS8509 | Switch not exhaustive: a missing union case, or an inaccessible closed-hierarchy subtype. |\n| CS8655 | Union contents are maybe-null and there's no `null` arm. |\n| CS8510 | Unreachable arm (a base arm after its subtypes, or `Car` before `Sedan`). |\n| CS0121 \u002F CS0411 | `with(...)` arguments don't pick overloads or infer type arguments. |\n| CS9370 \u002F CS9380 \u002F CS1519 | `union`\u002F`closed` used as an identifier. Escape it with `@`. |\n| CS9363 | A member with pointer parameters (for example an indexer) called outside `unsafe` (preview). |\n| CS9376 | A requires-unsafe parameterless constructor used where `new()`\u002F`struct` is required (preview). |\n| CS9392 | An explicit-layout field needs `safe`\u002F`unsafe` (preview). |\n| CS9401 \u002F CS0227 | `safe`\u002F`unsafe` modifiers or blocks used without `AllowUnsafeBlocks`. |\n| `SwitchExpressionException` | Run time: a `default` union (null contents) reached a switch with no `null` arm. |\n\n## Sources\n\n- What's new in C# 15: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Fwhats-new\u002Fcsharp-15\n- Collection expressions (arguments): https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Foperators\u002Fcollection-expressions#collection-expression-arguments\n- Spec, collection expression arguments: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Fcsharp-15.0\u002Fcollection-expression-arguments\n- Union types: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fbuiltin-types\u002Funion\n- Spec, unions: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Fcsharp-15.0\u002Funions\n- `closed` modifier: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fkeywords\u002Fclosed\n- Patterns (closed hierarchy and union patterns): https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Foperators\u002Fpatterns\n- Spec, closed hierarchies: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Fcsharp-15.0\u002Fclosed-hierarchies\n- Extension members (indexers): https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fkeywords\u002Fextension#extension-indexers\n- Spec, extension indexers: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Fcsharp-15.0\u002Fextension-indexers\n- Jump statements: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fstatements\u002Fjump-statements\n- Spec, labeled break\u002Fcontinue: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Fcsharp-15.0\u002Flabeled-break-continue\n- IDE0410: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Ffundamentals\u002Fcode-analysis\u002Fstyle-rules\u002Fide0410\n- Interface static members and runtime support: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fkeywords\u002Finterface#static-interface-members-and-runtime-support\n- Unsafe code (updated memory safety model): https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Funsafe-code\n- Spec, memory safety: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fproposals\u002Funsafe-evolution\n- Compiler options (enabling the memory safety rules): https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Flanguage-reference\u002Fcompiler-options\u002Flanguage#enable-the-updated-memory-safety-rules\n- Compiler breaking changes in .NET 11: https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcsharp\u002Fwhats-new\u002Fbreaking-changes\u002Fcompiler%20breaking%20changes%20-%20dotnet%2011\n- Roslyn language feature status: https:\u002F\u002Fgithub.com\u002Fdotnet\u002Froslyn\u002Fblob\u002Fmain\u002Fdocs\u002FLanguage%20Feature%20Status.md\n",{"name":5,"description":7},"master","def406f8dd4a1c5a918901d8bb5e40cd3289b268","skills\u002Fcsharp-15","https:\u002F\u002Fgithub.com\u002Fhmlendea\u002Fgithub-copilot-memories","https:\u002F\u002Fgithub.com\u002Fhmlendea","https:\u002F\u002Fhmlendea.go.ro","Writer of bugs","2026-11-15 05:17:25",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add hmlendea\u002Fgithub-copilot-memories --skill csharp-15",{"tool":38,"command":39},"bunx","bunx skills add hmlendea\u002Fgithub-copilot-memories --skill csharp-15",{"tool":41,"command":42},"pnpm","pnpm dlx skills add hmlendea\u002Fgithub-copilot-memories --skill csharp-15","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhmlendea\u002Fgithub-copilot-memories\u002Fblob\u002Fmaster\u002Fskills\u002Fcsharp-15\u002FSKILL.md",true,[],[47,54,61,68,75,82],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M7DZ7R9DC7Y1B1KWT1435HV1","ui-design-review","Use when designing, building, reviewing, or repairing user interfaces, or when UI work must be verified before delivery. Covers accessibility, touch and interaction, performance, style selection, layout and responsive behaviour, typography and colour, animation, forms and feedback, navigation, and charts, with a prioritised rule set, a native and mobile pre-delivery checklist, and a browser-driven audit procedure that reports evidence-ranked findings.","https:\u002F\u002Fgithub.com\u002Fhmlendea\u002Fgithub-copilot-memories\u002Fblob\u002Fmaster\u002Fskills\u002Fui-design-review\u002FSKILL.md",[],[],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M7DZ75BE238H0E0QCQMXC9PY","release-verification","Use after a release, publication, or deployment to verify the delivered artefact and observe the affected surfaces until the observation window is clean. Covers release identity, surface evidence, finding classification, observation cadence, and partial-verification reporting.","https:\u002F\u002Fgithub.com\u002Fhmlendea\u002Fgithub-copilot-memories\u002Fblob\u002Fmaster\u002Fskills\u002Frelease-verification\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M7DZ733Z56XN9H6MB7V489HN","pr-babysit","Use when monitoring a pull request or review cycle until it is ready to merge. Covers check observation, unresolved review threads, verification prior to resolution, and evidence-based completion.","https:\u002F\u002Fgithub.com\u002Fhmlendea\u002Fgithub-copilot-memories\u002Fblob\u002Fmaster\u002Fskills\u002Fpr-babysit\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7BDJ78RPSYKCP3PSS1558Z7","supply-chain-security","Use when assessing software supply chain exposure from dependency manifests, lockfiles, SBOMs, VEX records, licence declarations, package names, or CVE identifiers. Covers dependency and transitive risk, SBOM validation against the NTIA minimum elements in CycloneDX and SPDX, VEX status interpretation, licence compliance, typosquatting and dependency confusion, and CVE triage through CVSS 4.0, EPSS, SSVC 2.1, and the CISA KEV catalogue. Produces a prioritised, SLA-bound remediation assessment.","https:\u002F\u002Fgithub.com\u002Fhmlendea\u002Fgithub-copilot-memories\u002Fblob\u002Fmaster\u002Fskills\u002Fsupply-chain-security\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7BDJ14P86EFACYWB52VQJT5","secure-code-review","Use when performing a security-focused code review of a pull request, diff, file, or module, or when code touching authentication, authorisation, cryptography, input handling, deserialisation, file handling, or logging requires verification. Performs a structured review against OWASP ASVS 4.0.3 requirements and the CWE Top 25 (2024), producing findings mapped to ASVS controls and CWE identifiers with severity ratings and specific remediation guidance.","https:\u002F\u002Fgithub.com\u002Fhmlendea\u002Fgithub-copilot-memories\u002Fblob\u002Fmaster\u002Fskills\u002Fsecure-code-review\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7BDHT2VKHBWA9QANEGWYG65","secrets-management","Use when examining secret handling, credential exposure, vault or cloud secrets manager integration, environment-file hygiene, rotation policy, or credential access for agents and CI\u002FCD pipelines. Performs a structured secrets management assessment against the OWASP Secrets Management Cheat Sheet and NIST SP 800-57 Part 1 Rev 5, covering detection tooling, exposure routes, rotation automation, and centralised storage, without ever reproducing a secret value.","https:\u002F\u002Fgithub.com\u002Fhmlendea\u002Fgithub-copilot-memories\u002Fblob\u002Fmaster\u002Fskills\u002Fsecrets-management\u002FSKILL.md",[],[]]