Proposal: Allow scoped keyword for any reference type #7335
Replies: 1 comment
-
In this method, what can be done with async Task DoSomethingWith(scoped Memory<int> memory)
{
// can't accidentally - or willingly - do anything silly here anymore
} You actually can't do very much. You can't pass it to any other method because you don't know whether that method might retain a reference to it. The only way to allow use of other methods is to mark the parameters of those methods with the scoped keyword as well - and the parameters of the methods they call need to be marked as well, and so on and on. We also need scoped to be a part of the method signature, so that someone can't substitute a method without scoped at runtime, defeating the compile time check. In effect, scoped becomes viral, requiring virtually every conforming method to be correctly annotated before it would become useful - and that's a very large amount of churn for a relatively small benefit. Generally speaking, when someone asks for a language change to restrict code that would otherwise be permitted, the response is usually to suggest writing an analyzer. This is precisely what they're for. You can write such an analyzer yourself today (no waiting for years for a language change), reference it as a Nuget package from all your projects, and you can customize it for your context. IIRC, recent estimates in other threads have suggested that something like this would take about a day for a senior dev with experience writing an analyzer, and maybe a week for an intermediate dev who hasn't done it before. That compares favourably to the hundreds or thousands of hours that any language change requires. |
Beta Was this translation helpful? Give feedback.
-
Proposal
Allow the "scoped" keyword to be applicable to any reference type.
Motivation
C# does not currently provide any way to enforce a parameter of arbitrary reference type must not escape a method call.
Being able to impose and enforce such a restriction would greatly benefit cases where the caller holds some type of conceptual lifetime ownership over a parameter passed into a call, and may invalidate the object after the call has finished.
Motivating example
A classic example is object pooling:
we currently don't have any way that helps us with lifetime control in this context in any compiler-checked way, opening us op to plenty of potential bugs, or even malicious uses.
If we were able to use the scoped keyword for any reference type, we could avoid these issues altogether:
Beta Was this translation helpful? Give feedback.
All reactions