❔ 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
phaseshift
phaseshift2y ago
Not to state the obvious, but don't use Span 😁
LordKalma (CT7ALW)
I like views over memory, thank you 🙂
Aaron
Aaron2y ago
you can get around this by getting a pointer to the span and passing that into the lambda, if you really need to
MODiX
MODiX2y ago
Windows10CE#8553
REPL Result: Success
unsafe static int[] Main()
{
ReadOnlySpan<int> s = new int[] { 1, 2, 3, 4, 5 };
ReadOnlySpan<int>* sp = &s;
return Enumerable.Repeat(0, 5).Select((_, i) => (*sp)[i]).ToArray();
}
Main()
unsafe static int[] Main()
{
ReadOnlySpan<int> s = new int[] { 1, 2, 3, 4, 5 };
ReadOnlySpan<int>* sp = &s;
return Enumerable.Repeat(0, 5).Select((_, i) => (*sp)[i]).ToArray();
}
Main()
Result: int[]
[
1,
2,
3,
4,
5
]
[
1,
2,
3,
4,
5
]
Quoted by
<@!270457259065081856> from #void-spam (click here)
Compile: 663.034ms | Execution: 93.276ms | React with ❌ to remove this embed.
Aaron
Aaron2y ago
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
jcotton42
jcotton422y ago
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
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server