Copilot instructions
.github/instructions/csharp.instructions.mdCopilot instructions
Quality
59/100
Scores the file, not the repository.Length
2,023 words
14 headings · 0 code blocksRepository
18k
— · pushed 0 days agoLast changed
3 days ago
First indexed 3 days ago.12345# C# (managed code)67Conventions for C# changes across `src/`. Also apply `conventions` (all changes), `tests` (test8files), and any matching area file (`core-runtime`, `jit`, `system-net-*`, `extensions-*`,9`compression`, `cdac`). Native runtime code is covered by `native`.1011## Correctness & Safety1213### Error Handling & Assertions1415- **Use `Debug.Assert` for internal invariants, not exceptions.** For internal-only callers, assert assumptions rather than throwing `ArgumentException`. Prefer `Debug.Assert(value is not null)` over the null-forgiving operator (`!`).16- **Use `throw` for reachable error paths, `UnreachableException` for exhaustive switches.** When a code path might be hit at runtime, throw an exception rather than asserting. Use `throw new UnreachableException()` for default cases in exhaustive switches. Use `PlatformNotSupportedException` (not `NotSupportedException`) for platform gaps.17- **Include actionable details in exception messages.** Use `nameof` for parameter names. Include the unsupported type or unexpected value. Never throw empty exceptions.18- **Initialize output parameters in all code paths.** When a method has `out` parameters or pointer outputs (`bytesWritten`, `numLocals`), ensure they are initialized to a defined value in all error paths.19- **Use `ThrowIf` helpers over manual checks.** Use `ArgumentOutOfRangeException.ThrowIfNegative`, `ObjectDisposedException.ThrowIf`, etc. instead of manual if-then-throw patterns.20- **Don't swallow exceptions that mask unexpected errors.** Before adding a try/catch that silently discards exceptions (`catch { continue; }`, `catch { return null; }`), establish that the exception is a truly expected, recoverable condition rather than an unexpected error signaling a deeper problem (race conditions, memory corruption, build environment issues). Silently catching exceptions that "shouldn't happen" hides root causes and makes debugging harder. Let unexpected exceptions propagate or fail fast so the real issue gets investigated.2122### Thread Safety2324- **Use `Volatile` or `Interlocked` for cross-thread field access.** Fields written on one thread and read on another must use `Volatile<T>`, `Volatile.Read/Write`, or `Interlocked`. The `??=` operator is not thread-safe. `Nullable<T>` is not safe for caching (two-field struct tears). Do not use shared mutable arrays without synchronization.25- **Use `TickCount64` for timeout calculations.** Use `Environment.TickCount64` (long) instead of `Environment.TickCount` (int) to avoid integer overflow.2627### Security2829- **Guard integer arithmetic against overflow before mutating state.** Guard size computations involving multiplication (e.g., `newCapacity * sizeof(T)`) with checked arithmetic or an explicit bounds check. A `checked` expression is sufficient only when it throws before partial state mutation. When a guard is separated from the arithmetic it protects, add a brief comment connecting them.30- **Clean sensitive cryptographic data after use.** Always clear key material with `CryptographicOperations.ZeroMemory`. When using `PinAndClear` but copying to another buffer, clear the original too. Use non-short-circuit operators (`|`) in verification code to prevent timing leaks.31- **Don't proactively send credentials without opt-in.** Never send authentication credentials (especially Basic auth) before receiving a challenge.32- **Limit `stackalloc` to ~1KB total per method and validate size.** Don't stackalloc based on user-controlled or large input sizes. The total stackalloc budget across the entire method (not just the visible scope) must stay under ~1KB. If the method does a user callback, has unknown call depth, or potential for recursion, reduce the budget further or don't use stackalloc at all. Move stackalloc to just before usage, not before early returns. Use the bounded pattern `(length > Threshold) ? stackalloc[Threshold] : ArrayPool.Rent(length)` to safely cap user input.3334### Correctness Patterns3536- **Prefer safe code over unsafe micro-optimizations.** Do not introduce `Unsafe.As`, `Unsafe.AsRef`, or raw pointers without demonstrable performance need. Prefer Span-based APIs. If performance is the issue, prefer fixing the JIT. Never convert safe code to unsafe as a side effect of an unrelated functional change.37- **Use `Unsafe.BitCast` for same-size type punning between blittable types.** Prefer `Unsafe.BitCast<TFrom, TTo>` over `Unsafe.As<TFrom, TTo>` for type punning between unmanaged value types of the same size. For common cases, prefer safe alternatives (e.g., `BitConverter.SingleToInt32Bits` for `float`→`int`).38- **Handle `SafeHandle.IsInvalid` before `Dispose`.** Check `IsInvalid` (not null) on returned SafeHandles. Get the exception before calling `Dispose`, since Dispose might clear the error state.39- **Seal classes when `Equals` uses exact type matching.** If a class implements `Equals` with `GetType()` comparison, treat this as a potential bug when the class is unsealed. Sealing is usually the right fix, but not always — evaluate rather than applying it reflexively.40- **Use `Environment.ProcessPath` and `AppContext.BaseDirectory`.** Use these instead of `Process.GetCurrentProcess().MainModule?.FileName` and `Assembly.Location` for NativeAOT/single-file compatibility.41- **File name casing must match csproj references exactly.** Linux is case-sensitive. New source files must be listed in the `.csproj` if other files in that folder are explicitly listed.4243## Performance & Allocations4445### Measurement & Evidence4647- **Justify binary size increases with real-world measurements.** Changes that increase binary size require measured wall-clock improvements on real-world apps, not just instruction counts.48- **Avoid premature optimization with object pools and caches.** Do not introduce global caches or object pools without evidence they are needed. Prefer making the underlying operation faster.4950### Allocation Avoidance5152- **Avoid closures and allocations in hot paths.** When a lambda captures locals creating a closure, consider using a static delegate with a state parameter (value tuple). Avoid string concatenation; use span-based operations.53- **Pre-allocate collections when size is known.** Pass capacity to `Dictionary`, `HashSet`, `List` constructors when the expected count is available.54- **Structs in dictionaries need `IEquatable<T>` and `GetHashCode`.** Without these, the runtime falls back to boxing allocations for equality comparison.55- **Avoid Pinned Object Heap for non-permanent objects.** POH is never compacted and effectively gen2. Only use for objects surviving as long as the process.56- **Suppress `ExecutionContext` flow for infrastructure timers.** When allocating `Timer` or similar background infrastructure, suppress EC flow to avoid capturing unrelated `AsyncLocal`s that leak memory.5758### Code Structure for Performance5960- **Place cheap checks before expensive operations.** Order conditionals so cheapest/most-common checks come first. Move expensive work after early-exit checks.61- **Allocate resources lazily where possible.** Allocate expensive resources on first use, not during initialization. Avoid forcing type initialization during startup.62- **Extract throw helpers into `[DoesNotReturn]` methods.** Move throwing logic from error paths into separate static local functions or helper methods to allow the JIT to inline the success path.63- **Avoid O(n²) patterns in collections and hot paths.** Watch for linear scans inside loops, repeated `RemoveAt` in loops. Use `RemoveAll`, single-pass restructuring, or appropriate data structures.64- **Cache repeated accessor calls in locals.** Store the result of repeated property/getter calls in a local variable.65- **Consider scalability, not just throughput.** Evaluate whether data structures, caches, and locking strategies will hold up at high cardinality or under concurrent load. Watch for unbounded collection growth, lock contention that worsens with core count, and O(1) assumptions that break at scale.6667### Specific API Choices6869- **Use `AppContext.TryGetSwitch` with a static readonly property.** Cache AppContext switches in `static bool Prop { get; } = AppContext.TryGetSwitch(...)` so the JIT can dead-code-eliminate unreachable paths.70- **Do not cache `typeof` expressions in .NET Core.** `typeof(...)` is JITed into a constant; caching it is a de-optimization. Similarly, don't store `ArrayPool.Shared` in variables—it breaks devirtualization.71- **Use `CollectionsMarshal` for large value-type dictionary lookups.** Use `GetValueRefOrAddDefault` or `GetValueRefOrNullRef` to avoid copying large structs. Use `ValueListBuilder` on hot paths.72- **Use `sizeof` consistently.** A pass removed calls to the equivalent `Unsafe` helper; do not reintroduce them. Use `sizeof` rather than `Marshal.SizeOf` for blittable structs; it is more correct and significantly faster when no marshalling is involved.73- **Use the idiomatic `(uint)index >= (uint)length` bounds check.** The JIT recognizes this pattern and optimizes it. Slice spans before iterating to avoid per-element bounds checks.74- **Source generators must be properly incremental.** Do not store Roslyn symbols (`ISymbol`, `Compilation`) in incremental pipeline steps. Output must be deterministic with Ordinal-sorted lists.75- **Use `ValueListBuilder` for dynamic array building in BCL.** Use `ValueListBuilder<T>` (with pooling) or `ArrayBuilder<T>`. Use stackalloc for small sizes, array pool when too large.7677## API Design & Contracts7879- **Implementation must match the approved API shape.** Deferring portions of an approved API to incremental follow-up PRs is explicitly allowed, as is excluding specific members for technical reasons — unless the exclusion significantly impacts the design.80- **Use `internal` for new APIs pending API review.** If the API is needed immediately for implementation, mark it `internal` and file a review request separately. This governs code being submitted — an `api-proposal` prototype branch keeps the surface public so ref source generation can extract it.81- **Parameter names must match between ref and src.** Renaming a public API parameter (including case changes) is a breaking change affecting named arguments and late-bound scenarios.82- **Align exception types and validation order across platforms.** Validate arguments first (`ArgumentNullException`, then `ArgumentException`), then `PNSE`, then `ObjectDisposedException`, then perform the operation. Throw the same exception types on all platforms.83- **`Try` APIs should return `false` only for the common expected failure.** Throw for everything else (corruption, permissions, invalid arguments). Try methods must always throw on invalid arguments.84- **Don't expose mutable options after construction.** If values are captured at construction time, don't expose a mutable options object. Don't reference private field names or internal types in user-facing error messages.85- **Use `PlatformNotSupportedException` for platform limitations.** When an operation can't complete in the current environment but could on a different platform, throw PNSE. Don't impose artificial limits beyond OS capabilities.86- **.NET APIs should compensate for platform quirks.** Public APIs should work consistently across platforms. When adding overloads, check F# compatibility for implicit conversion or type inference ambiguities.87- **Follow the obsoletion process for deprecated APIs.** Pick the next available SYSLIB diagnostic ID, add `[Obsolete]`, and use `[EditorBrowsable(Never)]` with `[OverloadResolutionPriority(-1)]` for overload fixes.88- **New virtual methods must work with unoverridden derived types.** The default implementation must behave identically to calling the pre-existing equivalent APIs.89- **Avoid non-CLS-compliant integer types in public APIs.** Preserve `byte`, `int`, or `long` according to the required range; `byte` is valid even though it is unsigned. Use named types instead of `ValueTuple` across file boundaries.9091## Code Style & Formatting9293- **Use well-named constants instead of magic numbers.** No raw hex or decimal constants without explanation. Don't duplicate magic constants across files.94- **Use `var` only when the type is apparent from the right-hand side.** "Apparent" means the type is visible as a literal, constructor (`new Foo()`), or explicit cast — not merely "obvious from context." For example, `var x = y.ToString()` is not considered apparent because it's neither a literal nor a constructor. Follow the `.editorconfig` rules for `var` usage. Never use `var` for numeric types.95- **Use PascalCase for constants; descriptive names for booleans.** All constant locals and fields use PascalCase (except interop constants matching external names). Boolean fields should be positive and descriptive (`_hasCurrent` not `valid`).96- **Name methods to accurately reflect their behavior.** Update names when behavior changes. `Get*` implies a return value; use `Print*/Display*` for void. `ThrowIf` not `ThrowExceptionIf`.97- **Prefer early return to reduce nesting.** Use early returns for short/error cases to avoid unnecessary nesting. Put the error case first, success return last.98- **Avoid `using static` and `#region` in new code.** `using static` is costly when reading code outside IDEs (e.g., GitHub review). `#region` gets out of date quickly.99- **Place local functions at method end, fields first in types.** Local functions go at the end of the containing method. Fields are the first members declared in a type.100- **Narrow warning suppression to smallest scope.** Avoid file-wide `#pragma` suppressions. Disable only around the specific line that triggers the warning.101- **Use pattern matching and `is`/`or`/`and` patterns.** Prefer `is` patterns and C# pattern matching over manual type checks and comparisons. Use named parameters for boolean arguments.102- **Do not initialize managed fields to default values (CA1805).** The CLR zero-initializes all fields in managed code. Explicit `= false`, `= 0`, `= null` is redundant. (This does not apply to native C/C++ code, where fields and locals must be explicitly initialized.)103- **Sealed classes do not need the full Dispose pattern.** A simple `Dispose()` is sufficient since no derived class can introduce a finalizer.104105## Platform & Cross-Platform106107- **Use `BinaryPrimitives` for endianness-safe reads.** Use `ReadInt32LittleEndian`/`BigEndian` rather than pointer casts. Separate endianness-specific reads from target-endianness reads.108- **Use cross-platform vector APIs over ISA-specific intrinsics.** Prefer `Vector128/256/512.IsHardwareAccelerated` and cross-platform APIs (`.Shuffle`, `.Min`) over `Avx512BW`, `SSE2`. Use the bit manipulation APIs exposed directly on numeric types (e.g., `int.PopCount`, `long.LeadingZeroCount`) rather than `BitOperations` for portable bit manipulation.109
Also in dotnet/runtime
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| dotnet/runtime.github/instructions/system-net-interop.instructions.md · 18k | Copilot instructions | stylearchperformance | 56/100 | 3 days ago | |
| dotnet/runtime.github/instructions/extensions-logging.instructions.md · 18k | Copilot instructions | securityperformance | 44/100 | 3 days ago | |
| dotnet/runtime.github/instructions/native.instructions.md · 18k | Copilot instructions | lint-formatstylearchperformance | 76/100 | 3 days ago | |
| dotnet/runtime.github/instructions/system-net-security.instructions.md · 18k | Copilot instructions | securityperformancedeployment | 48/100 | 3 days ago | |
| dotnet/runtime.github/copilot-instructions.md · 18k | Copilot instructions | buildteststylearch+2 | 78/100 | 3 days ago | |
| dotnet/runtime.github/instructions/cdac.instructions.md · 18k | Copilot instructions | typesgitapidocs | 52/100 | 3 days ago | |
| dotnet/runtime.github/instructions/compression.instructions.md · 18k | Copilot instructions | testlint-formatstylesecurity+1 | 60/100 | 3 days ago | |
| dotnet/runtime.github/instructions/conventions.instructions.md · 18k | Copilot instructions | stylearchagent-behaviourdocs | 56/100 | 3 days ago | |
| dotnet/runtime.github/instructions/core-runtime.instructions.md · 18k | Copilot instructions | styleperformance | 43/100 | 3 days ago | |
| dotnet/runtime.github/instructions/extensions-caching.instructions.md · 18k | Copilot instructions | styleperformanceagent-behaviour | 48/100 | 3 days ago | |
| dotnet/runtime.github/instructions/extensions-common.instructions.md · 18k | Copilot instructions | styledependencies | 48/100 | 3 days ago | |
| dotnet/runtime.github/instructions/extensions-configuration.instructions.md · 18k | Copilot instructions | no sections | 44/100 | 3 days ago | |
| dotnet/runtime.github/instructions/extensions-di.instructions.md · 18k | Copilot instructions | teststyletesting-strategy | 52/100 | 3 days ago | |
| dotnet/runtime.github/instructions/extensions-hosting.instructions.md · 18k | Copilot instructions | teststyleagent-behaviour | 52/100 | 3 days ago | |
| dotnet/runtime.github/instructions/extensions-options.instructions.md · 18k | Copilot instructions | style | 48/100 | 3 days ago | |
| dotnet/runtime.github/instructions/jit.instructions.md · 18k | Copilot instructions | buildgit | 29/100 | 3 days ago | |
| dotnet/runtime.github/instructions/system-net-common.instructions.md · 18k | Copilot instructions | styledependenciesapi | 48/100 | 3 days ago | |
| dotnet/runtime.github/instructions/system-net-http.instructions.md · 18k | Copilot instructions | styleperformance | 52/100 | 3 days ago | |
| dotnet/runtime.github/instructions/system-net-quic.instructions.md · 18k | Copilot instructions | teststyleperformance | 56/100 | 3 days ago | |
| dotnet/runtime.github/instructions/system-net-sockets.instructions.md · 18k | Copilot instructions | styleagent-behaviour | 48/100 | 3 days ago |
Diff against .github/instructions/system-net-interop.instructions.md Diff against .github/instructions/extensions-logging.instructions.md Diff against .github/instructions/native.instructions.md Diff against .github/instructions/system-net-security.instructions.md Diff against .github/copilot-instructions.md Diff against .github/instructions/cdac.instructions.md Diff against .github/instructions/compression.instructions.md Diff against .github/instructions/conventions.instructions.md Diff against .github/instructions/core-runtime.instructions.md Diff against .github/instructions/extensions-caching.instructions.md Diff against .github/instructions/extensions-common.instructions.md Diff against .github/instructions/extensions-configuration.instructions.md Diff against .github/instructions/extensions-di.instructions.md Diff against .github/instructions/extensions-hosting.instructions.md Diff against .github/instructions/extensions-options.instructions.md Diff against .github/instructions/jit.instructions.md Diff against .github/instructions/system-net-common.instructions.md Diff against .github/instructions/system-net-http.instructions.md Diff against .github/instructions/system-net-quic.instructions.md Diff against .github/instructions/system-net-sockets.instructions.md
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| chihebnabil/lovable-boilerplate.github/instructions/global.instructions.md · 63 | Copilot instructions | buildlint-formatstylearch+4 | 100/100 | 3 days ago | |
| louislam/uptime-kuma.github/copilot-instructions.md · 90k | Copilot instructions | setupbuildtestlint-format+9 | 100/100 | 3 days ago | |
| HerringtonDarkholme/megarepo.github/copilot-instructions.md · 17 | Copilot instructions | setupbuildtestlint-format+7 | 100/100 | 3 days ago | |
| dotnet/roslyn.github/instructions/Compiler.instructions.md · 21k | Copilot instructions | buildteststylearch+3 | 99/100 | 3 days ago | |
| JCodesMore/ai-website-cloner-template.github/copilot-instructions.md · 31k | Copilot instructions | buildlint-formatstylearch+3 | 97/100 | 2 days ago | |
| dotnet/roslyn.github/copilot-instructions.md · 21k | Copilot instructions | buildteststylearch+3 | 97/100 | 3 days ago | |
| bagisto/bagisto.github/copilot-instructions.md · 28k | Copilot instructions | setupbuildteststyle+5 | 97/100 | 3 days ago | |
| darkmatter/nixmac.github/copilot-instructions.md · 24 | Copilot instructions | setupbuildtestlint-format+8 | 96/100 | 3 days ago |
