-
Notifications
You must be signed in to change notification settings - Fork 6k
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
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -83,3 +83,30 @@ 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. | ||||||
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(); | ||||||
var d = p.M(); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should this use
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Indeed - However, because I generally used the exact same example as the one showing the CS8170, I also updated the original with this suggestion. |
||||||
} | ||||||
} | ||||||
``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is great, but I think it's worth pointing out the danger here: you really need to know that the ref can escape safely.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please check with the latest, as I added the "warning" for being sure about the safety of leaving the scope.
Let me know, please if there's some other wording you think would suit this better.