Unsafe rules

Pointer, reinterpret, and blittability rules.

Rules

RuleTitleCode fix
E128112Do not reinterpret one type as another with Unsafe.AsYes
E128113Use the unaligned Unsafe read and write methodsYes
E128114Index the array instead of bypassing its bounds checkYes
E128115Do not reinterpret between bool and intYes
E128118Do not reinterpret bytes as a non-blittable typeYes
E128119Use an inline array instead of a fixed-size bufferYes
E128120Do not skip local initialization without a measured reasonYes
E128125Pin the object explicitly with fixedNo
E128126Do not write to a string through a fixed pointerNo
E128127Do not create a null managed referenceNo
E128128Keep the delegate alive while native code holds its function pointerNo
E128129Do not move a type that holds references through UnsafeNo
E128136Do not pair a pointer parameter with a separate length parameterNo
E128137Do not bind to a non-public BCL member through reflectionNo
E128138Do not build dynamic methods with raw ILNo
E128139Do not move a non-blittable type through an unaligned accessYes
E128200Do not declare a function pointer typeNo
E128254Do not write a static readonly field through reflectionNo
E128261Byte-wise access of a padded structNo

Rule details

E128112: Do not reinterpret one type as another with Unsafe.As

Flags Unsafe.As<TFrom, TTo>(ref value) in two cases. The first is a source or target that is a reference type, or a type parameter that is not unmanaged. The second is two fixed-size value types of the same size. Unsafe.BitCast checks the size and rejects a reference type. The rule stays silent for two value types of different sizes when the result is used as a reference (assigned to, passed by ref, or bound to a ref local). The rule also stays silent when the target has no Unsafe.BitCast (before .NET 8). The code fix rewrites the call to Unsafe.BitCast<TFrom, TTo>(value) only when both types are unmanaged.

// Before (warns)
int bits = Unsafe.As<float, int>(ref value);

// After
int bits = Unsafe.BitCast<float, int>(value);

E128113: Use the unaligned Unsafe read and write methods

Flags Unsafe.Read<T> and Unsafe.Write<T>. The plain overloads assume an aligned address. A misaligned address faults or tears the value. The code fix renames the call to Unsafe.ReadUnaligned or Unsafe.WriteUnaligned.

E128114: Index the array instead of bypassing its bounds check

Flags Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), index) on a single-dimension array. The pattern removes the bounds check, and the JIT already elides the check in a simple loop. The code fix rewrites the call to array[index] and adds parentheses where the array expression needs them.

E128115: Do not reinterpret between bool and int

Flags Unsafe.As<bool, int> and Unsafe.As<int, bool> when the result is not used as a reference. A bool occupies one byte and an int occupies four bytes. The reinterpretation reads adjacent memory. The code fix rewrites the call to a comparison or a ternary. The fix normalizes the value, so any nonzero int becomes true.

E128118: Do not reinterpret bytes as a non-blittable type

Flags MemoryMarshal.Read<T> and MemoryMarshal.Cast<TFrom, TTo> when the interpreted type is not blittable. A type is not blittable when it holds a reference, or when it is or contains a bool or a decimal. The code fix applies only to MemoryMarshal.Read<bool>(source). It rewrites the call to (source[0] != 0).

E128119: Use an inline array instead of a fixed-size buffer

Flags a field declared with fixed, including a declaration with several buffers or a constant size, when the target defines InlineArrayAttribute and the language version is C# 12 or later. A fixed-size buffer has no bounds checks and no default zeroing. The code fix applies only to a single-declarator field that nothing references. It replaces the field with a nested [InlineArray] struct named {Field}Buffer. The nested struct takes the accessibility of the field.

E128120: Do not skip local initialization without a measured reason

Flags Unsafe.SkipInit(out local). The local keeps whatever the stack holds. The rule accepts the call only after a benchmark shows a win. The code fix replaces the call with T name = default;, or with name = default; for an existing local.

E128125: Pin the object explicitly with fixed

Flags Unsafe.AsPointer(ref value) outside a fixed statement. The rule stays silent for a plain local or a by-value parameter only when the pointer does not escape. A pointer escapes when the method returns it, or when an assignment stores it into a field, a property, or an element. The call takes no pin, so the GC can move a heap object while the pointer is live. No code fix. Use a fixed block around the pointer.

E128126: Do not write to a string through a fixed pointer

Flags a fixed (char* p = text) block when the body writes through p. A write is an assignment, an increment, or a ref or out argument on p[i], *p, or *(p + n). A read-only pin is silent. A copy of the pointer in another variable is not followed. A string is immutable, and the runtime shares interned strings between callers. No code fix. Build a new string instead.

E128127: Do not create a null managed reference

Flags Unsafe.NullRef<T>() and Unsafe.AsRef<T> on a null pointer. The rule stays silent when a ref return gives NullRef back as a “not found” sentinel. A null byref has no valid referent, and any read or write through it corrupts memory. No code fix. Use a null object, an empty span, or a nullable value instead.

E128128: Keep the delegate alive while native code holds its function pointer

Flags Marshal.GetFunctionPointerForDelegate when the delegate is a temporary (new, a lambda, or a method group), or when it is a local or a parameter that nothing stores in a field, property or element, and nothing passes to GC.KeepAlive, GCHandle.Alloc, or a collection method such as Add, TryAdd, Push, Enqueue, or Insert. A plain call that does not root the delegate no longer counts. The call does not root the delegate, so the GC can collect it while native code holds the pointer. No code fix. Keep the delegate in a field or a GCHandle for the lifetime of the pointer.

E128129: Do not move a type that holds references through Unsafe

Flags Unsafe.Copy, Unsafe.Write, and Unsafe.WriteUnaligned where the moved type holds a reference. It also flags Unsafe.CopyBlock, CopyBlockUnaligned, InitBlock, and InitBlockUnaligned when an argument is a pointer to a type that holds a reference. The move bypasses the write barrier, so a reference can miss a GC update. A void* argument and an unmanaged type are silent. No code fix. The right replacement depends on whether the caller needs a deep or a shallow copy.

E128136: Do not pair a pointer parameter with a separate length parameter

Flags a method with a pointer parameter and another parameter of an integer or pointer-width type. The pair invites a length that does not match the buffer.

No code fix. Replace the pair with a single Span<T> or ReadOnlySpan<T> parameter.

E128137: Do not bind to a non-public BCL member through reflection

Flags Type.GetMethod, GetField, GetProperty, GetEvent, GetMember, GetConstructor, or GetNestedType when a BindingFlags argument names a non-public member and the receiver is typeof(X) or value.GetType(). The target is the static type of value. A Type variable carries no target type, so the rule stays silent. A private BCL member can change or disappear between runtime versions.

No code fix. Use the public API, or a package that owns the access.

The analyzer treats a type as a BCL type only when its assembly name starts with System or Microsoft and its public key token belongs to a known framework key. A user assembly named like System.Foo has no framework key and stays silent.

E128138: Do not build dynamic methods with raw IL

Flags every call on System.Reflection.Emit.ILGenerator. The emitted opcodes are unchecked by the compiler and are hard to read.

No code fix. Use Expression.Lambda or a source-generated method.

E128139: Do not move a non-blittable type through an unaligned access

Flags Unsafe.ReadUnaligned<T> and Unsafe.WriteUnaligned<T> when T is not blittable. A type is not blittable when it holds a reference, or when it is or contains a bool or a decimal. The bit pattern of such a type is not portable.

// Before (warns)
bool value = Unsafe.ReadUnaligned<bool>(ref source);

// After
bool value = source != 0;

The code fix applies to Unsafe.ReadUnaligned<bool> only.

E128200: Do not declare a function pointer type

Flags a delegate* type in a field, a parameter, a return type, or a local. This covers the managed and the unmanaged forms. A function pointer carries no lifetime or calling-convention guarantee, and native code can call a collected target. Use a delegate type. No code fix.

// Before (warns)
delegate*<int, int> twice = &Twice;

// After
Func<int, int> twice = Twice;

E128254: Do not write a static readonly field through reflection

Flags a FieldInfo.SetValue or SetValueDirect call whose field is a static readonly field of a type outside the framework.

The field resolves through several forms. The receiver is a GetField call on typeof(T), on value.GetType(), or on a Type local that resolves to either. The receiver is also a FieldInfo local initialized or assigned once from that call, and the assignment must run before the write. A null-conditional call is read the same way. A FieldInfo that arrives from a parameter stays silent.

The rule reads the BindingFlags argument. A flag set must fold to a constant. A literal flag set and a const BindingFlags field must name Static, and they must name Public for a public field or NonPublic for a nonpublic field. A flag set held in a runtime local stays silent. A GetField call with no flag argument searches public fields only.

The runtime inlines a static readonly field into every reader. A reflective write can reach a non-inlined reader and miss each inlined one.

No code fix. Make the field a mutable static, or pass the value to each reader.

E128261: Byte-wise access of a padded struct

Flags MemoryMarshal.AsBytes, MemoryMarshal.Cast, Unsafe.As, Unsafe.Copy, Buffer.BlockCopy, and Marshal.StructureToPtr when the source struct carries explicit-layout padding. The rule computes the padding from the [FieldOffset] values and the declared Size. No code fix, because the layout change belongs to the author.

The rule reads LayoutKind.Explicit only. It does not read the Pack value. A sequential layout, a nested struct field, and a pointer or bool field stay silent.