❔ Capturing value-types by value (i.e., making a copy) in λs. Or rather, using a Span<T> in a λ.
I have some code using a
Span<T>
. I wanted to use some LINQ with it (e.g. the Enumerable.Range.Select
method), but whenever I try to use the Span<T>
object inside a lambda, I get the error CS8175:
Error CS8175 Cannot use ref local <mySpanVariable>
inside an anonymous method, lambda expression, or query expression.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs8175
How can I work around this?7 Replies
Not to state the obvious, but don't use Span 😁
I like views over memory, thank you 🙂
you can get around this by getting a pointer to the span and passing that into the lambda, if you really need to
Windows10CE#8553
REPL Result: Success
Result: int[]
Quoted by
<@!270457259065081856> from #void-spam (click here)
Compile: 663.034ms | Execution: 93.276ms | React with ❌ to remove this embed.
very important though, this means you cannot return the enumerable directly
you have to collect it or use it somewhere in the same method you made it, due to it containing a pointer to somewhere on the stack
would Memory<T> work for you here?
in any case, the issue is that the closure created by the lambda is a reference type
and Spans cannot be placed on the heap
Memory can be however
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.