ReSharper 2020.3 Help

Code Inspection: Redundant fixed pointer declaration

Fixed size buffer fields are struct members available in unsafe contexts that represent C style inline arrays. Such fields are primarily used for interoperation with native code.

Before C# 7.3 accessing the elements of a fixed size buffer which can possibly reside in memory movable by GC was allowed only after pinning the buffer with the fixed statement, while fixed size buffers guaranteed to be located in non-movable memory could be indexed directly.

public unsafe struct MyBufferWrapper { public fixed byte Buffer[4]; public int Foo() => Buffer[0] + Buffer[1] + Buffer[2] + Buffer[3]; // error before C# 7.3 public int Bar() { fixed (byte* ptr = Buffer) { return ptr[0] + ptr[1] + ptr[2] + ptr[3]; // ok } } }

The requirement to introduce auxiliary fixed pointer declaration is unjustified for cases when fixed size buffer is only used to access its elements, because unless address of the buffer is stashed somewhere indexing is always safe.

C# 7.3 removed the unneeded limitation for indexing movable fixed size buffers and made their use more natural:

public unsafe struct MyBufferWrapper { public fixed byte Buffer[4]; public int Foo() => Buffer[0] + Buffer[1] + Buffer[2] + Buffer[3]; // ok since C# 7.3 public int Bar() { byte* ptr = Buffer; // error: taking address of the fixed size buffer still requires pinning return ptr[0] + ptr[1] + ptr[2] + ptr[3]; } }

ReSharper detects places where the use of the fixed statement is not required and provides a quick-fix to remove redundant fixed pointer declaration.

Last modified: 08 March 2021