Debbugger equivocated evaluation of span instance right before calling MemoryMarshal.AsBytes

40 Views Asked by At

I think this is a debugger evaluation bug, when you try to evaluate an span instance right before calling MemoryMarshal.AsBytes(ReadOnlySpan<T>) the debugger exhibits the wrong values for the positon 0 at the span indexer.

/* .csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
*/

// Program.cs
#define INVOKE_BUG
using System.Runtime.InteropServices;

Span<Location> span = new Location[1];
span[0] = new(3);

#if INVOKE_BUG
Console.WriteLine(span[0].AtX); // prints out 3
// visual studio 2022 debugger indicates the following evaluations:
//
// a: (new System.SpanDebugView<Location>(span).Items[0]).AtX | exhibits 0
// b: span[0].AtX                                             | exhibits 3
//
// while (a) happens when you mouse-hover span > [0] > AtX > 0
//       (b) happens when you mouse-hover the AtX in span[0].AtX at Console.WriteLin(...
//
// with the debug in this line |
//                             v
var bin = MemoryMarshal.AsBytes(span);
#elif TEST_2
// bug doenst happens both (a) and (b) results 3
global::System.Console.WriteLine(span.ToString());
#else
// bug doesnt happens, both (a) and (b) results 3
var bin = Span<byte>.Empty;
#endif

record struct Location(int AtX);

I catched this strange behavior when debugging a Marshal operation like this one, the logic was fine so i reduced into a re-creatable version and the weird evaluations persisted.

Im trying to understand why does that happens and if i should seek support about it

0

There are 0 best solutions below