I would like to use Linq expression trees to call the indexer of a Span<T>
. The code looks like:
var spanGetter = typeof(Span<>)
.MakeGenericType(typeof(float)).GetMethod("get_Item");
var myFloatSpan = Expression.Parameter(typeof(Span<float>), "s");
var myValue = Expression.Call(
myFloatSpan,
spanGetter,
Expression.Constant(42));
var myAdd = Expression.Add(
myValue,
Expression.Constant(13f));
Yet, this code fails because myValue
is of type Single&
(aka ref struct
) instead of type Single
(aka struct
).
How to evaluate a Span<T>
from an expression tree?
Expression<Func<float>> expr = () => new Span<float>()[42];
fails with An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference. Moreover,Span<T>
can't be used as an generic argument, so C# won't let you declare variable of typeExpression<Func<Span<float>, float>>
.