Skip to content

Unexpected error when using Span defined with old ref safety rules #80244

@RikkiGibson

Description

@RikkiGibson

We got a report from @brianrob that a new ref safety error is being reported on upgrade at the following location
https://github.com/microsoft/perfview/blob/049ed4f9462f39e2212a500fe80d55f1821dbb66/src/TraceEvent/EventPipe/SpanReader.cs#L45

(CoreCompile target) ->
         E:\perfview\src\TraceEvent\EventPipe\SpanReader.cs(52,28): error CS8157: Cannot return 'ret' by reference because it was initialized to a value that cannot be returned by reference [
       E:\perfview\src\TraceEvent\TraceEvent.csproj::TargetFramework=netstandard2.0]

Notably the compilation which is failing, has a netstandard2.0 reference to System.Memory and therefore the Span indexer uses the old ref safety rules.

I think the above case may have been exposed by #79447, the error is not reported when replaying the complog before that PR, and is reported afterwards.

However I think the below repro is showing a more general bug which may have already existed for some time.

<-- MyLib/MyLib.csproj -->
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework> <!-- Change to net8.0 to remove the error (new ref safety rules) -->
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
// MyLib/Class1.cs
namespace MyLib;

public ref struct RS
{
    public ref byte this[int i] => throw null!;
}
// lab.cs
#:project ./MyLib
#:property TargetFramework=net9.0

using MyLib;

Console.WriteLine();

static ref byte M1(RS rs)
{
    ref byte ret = ref rs[1];
    return ref ret; // unexpected error when referencing net6.0
}

static ref byte M2(RS rs)
{
    return ref rs[1]; // no error with either net6.0 or 8.0
}

Metadata

Metadata

Assignees

Type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions