Skip to content

Add an example of using UnscopedRefAttribute to fix CS8170 #47078

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion docs/csharp/language-reference/compiler-messages/cs8170.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class Other
public void Method()
{
var p = new Program();
var d = p.M();
ref int d = ref p.M();
}
}
```
Expand Down Expand Up @@ -83,3 +83,31 @@ public class Other
}
}
```

Another approach is to use the <xref:System.Diagnostics.CodeAnalysis.UnscopedRefAttribute?displayProperty=nameWithType> attribute. It will mark the reference to be allowed to escape the scope.<br/>
Use this only when you know that it is safe for the reference to leave the scope.
Below is the example of applying <xref:System.Diagnostics.CodeAnalysis.UnscopedRefAttribute?displayProperty=nameWithType> to `int M()` method, which fixes the CS8170:

```csharp
using System.Diagnostics.CodeAnalysis;

struct Program
{
public int d;

[UnscopedRef]
public ref int M()
{
return ref d; // No error - ref is valid to escape the scope in this line of that method
}
}

public class Other
{
public void Method()
{
var p = new Program();
ref int d = ref p.M();
}
}
```