Using stackalloc span in if statement
Hi I’m trying to use a span allocated on the stack of the function but it fails unless I reference the stack outside of an if statement. An example of this compiler error can be seen at https://sharplab.io/#v2:D4AQTAjAsAUCAMACEEB0BJA8gblrEAzMmIgMKIDesiNyRIALIgLIAUAlJdbTwEoCmAQwAmmAHYAbAJ4BlAA6CxAHgDGAC0EAnAHyJhAS00z+CzYIAuAe02kNmgM6IAvIgDa3Hp8QAFC2tQAIob8KlaasiZaFta2WgA0Hl60vub+AIIS5kGaIWERptE2dok8ALq4MEmIAiLi0vKKqna6CqnOiABEqN0dFVUltABm1kLqiKy8igDm/Ij2/FMAtvxi5oj6Yoit/vIS+uasKf5HxgVh7OwDNFSVVbQ1opKyCsrqWror5uHt267zS59yldPPpBuMAISsT7hVAAGRWUzaThcEEQADI0YhoVJXPBSs4XAByAD0hIuwJ4NzuSWx7WxqAAKpp9IsAKJiYSsAxGSJmMKxBzsPrUxAAXwptAlNBQAE4oasYQzLDIvhsphwhcDxbcaNrRUA=
Is this at all possible to achieve?
SharpLab
C#/VB/F# compiler playground.
4 Replies
From my understanding compiler is complaining because it is worried about
entry
escaping outside of its valid context. You may add scoped
keyword to entry
(scoped ReadOnlySpan<char> entry
) to make it scoped local to make compiler happy. It should also work if MemoryExtensions.TrimEnd
took scoped trimChars
, but seems like that is not what we have today.
This can be a good reading: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-11.0/low-level-struct-improvements#scoped-locals
Some language folks might chime in and add some details too :catcomf:Thanks I appreciate, I'll have to read through that post as I don't understand how it could be used outside of its valid context but maybe that's just my misunderstanding of spans really
For example you might
return entry;
that ends up exposing invalid value outside of the method. scoped
local introduced to ensure that the variable will not escape current scope. I believe it is also partially backward-compatibility reason involved that we need to explicitly put keyword for it.ah ok, that makes more sense as I was wracking my brain to figure out how it could have escaped it. Putting
scope ... entry
did the trick though so thank you very much