diff --git a/docs/csharp/language-reference/compiler-messages/cs8170.md b/docs/csharp/language-reference/compiler-messages/cs8170.md index 660b91c6fd8b1..56c0d5bfdd24a 100644 --- a/docs/csharp/language-reference/compiler-messages/cs8170.md +++ b/docs/csharp/language-reference/compiler-messages/cs8170.md @@ -35,7 +35,7 @@ public class Other public void Method() { var p = new Program(); - var d = p.M(); + ref int d = ref p.M(); } } ``` @@ -83,3 +83,31 @@ public class Other } } ``` + +Another approach is to use the attribute. It will mark the reference to be allowed to escape the scope.
+Use this only when you know that it is safe for the reference to leave the scope. +Below is the example of applying 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(); + } +} +```