Start Debugging

How to read a Span or ref struct property with reflection in C#

PropertyInfo.GetValue throws NotSupportedException for Span and ref struct properties. Use a typed delegate, UnsafeAccessor, or a compiled expression that converts the value before returning.

This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process

Short answer: you cannot get a Span<T>, ReadOnlySpan<T>, or any other ref struct property out of PropertyInfo.GetValue, because the result would have to be boxed into object and byref-like types cannot be boxed. Since .NET 7, GetValue, MethodInfo.Invoke, and MethodInvoker throw NotSupportedException: Specified method is not supported. instead. If you know the type at compile time, call the getter through a typed delegate (getter.CreateDelegate<Func<Match, ReadOnlySpan<char>>>(), legal since .NET 9 because Func<T, TResult> is declared with allows ref struct) or through [UnsafeAccessor]. If you only know the type at runtime, as an object inspector does, compile an expression tree that reads the property and converts it to something boxable inside the same frame (a string, a T[], a dictionary of the struct’s own properties) before returning. Everything below was run on .NET SDK 11.0.100 with the 11.0.0 runtime on macOS arm64, C# 15.

The exception you get, and why its message is useless

The question comes up in this Stack Overflow thread about building an object inspector. System.Text.RegularExpressions.Match is a good test subject because it exposes a ReadOnlySpan<char> ValueSpan next to ordinary properties:

// .NET 11.0.0, C# 15
using System.Reflection;
using System.Text.RegularExpressions;

Match match = new Regex(@"\d+").Match("testing 123");
PropertyInfo prop = typeof(Match).GetProperty(nameof(Match.ValueSpan))!;
Console.WriteLine($"Runtime: {Environment.Version}, IsByRefLike: {prop.PropertyType.IsByRefLike}");

try { prop.GetValue(match); }
catch (Exception ex) { Console.WriteLine($"GetValue: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); }

try { prop.GetMethod!.Invoke(match, null); }
catch (Exception ex) { Console.WriteLine($"Invoke: {ex.GetType().Name}: {ex.Message}"); }

try { MethodInvoker.Create(prop.GetMethod!).Invoke(match); }
catch (Exception ex) { Console.WriteLine($"MethodInvoker: {ex.GetType().Name}: {ex.Message}"); }

Output:

Runtime: 11.0.0, IsByRefLike: True
GetValue: NotSupportedException: Specified method is not supported.
   at System.Reflection.RuntimeMethodInfo.ThrowNoInvokeException()
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Program.<Main>$(String[] args) in .../Program.cs:line 13
Invoke: NotSupportedException: Specified method is not supported.
MethodInvoker: NotSupportedException: Specified method is not supported.

The message names no type and no property, which is why it is hard to search for. The stack trace is the giveaway: ThrowNoInvokeException is the runtime refusing to invoke a method whose return type is byref-like. Every reflection invoke path returns object, and producing an object from a ReadOnlySpan<char> means boxing it onto the heap. A span on the heap could outlive the stack memory it points at, which is exactly what the ref struct rules exist to prevent. Before .NET 7 some of these calls did not throw and could hand back garbage; the .NET 7 breaking change note on reflection invoke made PropertyInfo.GetValue and friends throw NotSupportedException for byref-like types instead.

MethodInvoker (added in .NET 8) does not help either: its Invoke overloads also return object. Real reflection support for byref-like types is still an open request, tracked in dotnet/runtime#10057 and dotnet/runtime#45152, neither of which shipped in .NET 11.

So the rule for every workaround is the same: the span must be consumed by code that knows its static type, and only a boxable result may cross back into object land. Which tool you pick depends on how much you know at compile time.

When you know the property type at compile time

A typed delegate over the getter

Since .NET 9, the generic parameters of Func<> and Action<> are declared with allows ref struct. You can check it on the running runtime:

// .NET 11.0.0
Console.WriteLine(typeof(Func<,>).GetGenericArguments()[1].GenericParameterAttributes);
// Covariant, AllowByRefLike

That means Func<Match, ReadOnlySpan<char>> is a legal type, and MethodInfo.CreateDelegate can bind the getter to it. No boxing happens because the delegate’s signature carries the real return type:

// .NET 11.0.0, C# 15 (needs .NET 9+)
var getValueSpan = typeof(Match)
    .GetProperty(nameof(Match.ValueSpan))!
    .GetMethod!
    .CreateDelegate<Func<Match, ReadOnlySpan<char>>>();

ReadOnlySpan<char> digits = getValueSpan(match);
Console.WriteLine(digits.ToString()); // 123

Create the delegate once and cache it; after that, each read is an ordinary delegate call with no reflection involved. On .NET 8 and earlier you have to declare your own delegate type (delegate ReadOnlySpan<char> SpanGetter(Match m);) because the BCL Func did not allow ref structs yet.

UnsafeAccessor, including for non-public getters

If the property is private or internal, [UnsafeAccessor] (introduced in .NET 8) gives you a direct, Native AOT friendly call into the getter. Name the accessor after the compiler-generated getter method:

// .NET 11.0.0, C# 15
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;

static class Accessors
{
    // ValueSpan is declared on Capture, Match's base class.
    [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "get_ValueSpan")]
    public static extern ReadOnlySpan<char> ValueSpan(Capture c);
}

Console.WriteLine(Accessors.ValueSpan(match).ToString()); // 123

Note the parameter type. The first version of this test took Match m and failed at the first call with System.MissingMethodException: Method not found: 'System.Text.RegularExpressions.Match.get_ValueSpan'. UnsafeAccessor looks the member up on the exact type of the first parameter and does not walk base classes, and ValueSpan is declared on Capture. PropertyInfo.DeclaringType tells you which type to use. If you want the broader picture of how UnsafeAccessor compares with reflection, see UnsafeAccessor vs reflection performance, and for the struct-specific trap where writes silently go to a copy, see why an UnsafeAccessor field write has no effect on a struct.

A generic expression-tree getter

The approach from the original question also works, as long as the generic parameter carries allows ref struct:

// .NET 11.0.0, C# 15
using System.Linq.Expressions;

static T GetProperty<T>(object target, string name) where T : allows ref struct
{
    var arg = Expression.Parameter(typeof(object));
    var expr = Expression.Property(Expression.Convert(arg, target.GetType()), name);
    return Expression.Lambda<Func<object, T>>(expr, arg).Compile()(target);
}

Console.WriteLine(GetProperty<ReadOnlySpan<char>>(match, "ValueSpan").ToString()); // 123

This compiles a new delegate on every call, so cache the compiled Func<object, T> per property in real code. And it still requires T at compile time, which is the part the object-inspector scenario cannot provide.

When you only know the type at runtime

An inspector, a debugger visualizer, a logging enricher or a test-diff tool walks GetProperties() and has nothing but a PropertyInfo. You cannot write var x = <something of unknown ref struct type> in C#, and you cannot call GetProperty<T> with MakeGenericMethod and hand the result back, because the return value would still need to land in object.

What you can do is generate code at runtime that has the static type, read the property there, and convert it to a boxable value before returning. Two runtime facts make that possible on .NET 9 and later:

  1. MethodInfo.MakeGenericMethod accepts a ref struct type argument when the method’s type parameter is declared allows ref struct. Without that anti-constraint it throws ArgumentException: GenericArguments[0], 'Plain', on 'System.String NoAllow[T](T)' violates the constraint of type 'T'.
  2. Compiled expression trees can hold ref struct values in intermediate expressions and in Expression.Variable locals, as long as nothing in the tree converts them to object.

Here is a reader that handles Span<T>, ReadOnlySpan<T>, and arbitrary user-defined ref structs:

// .NET 11.0.0, C# 15 (works on .NET 9 and later: needs "allows ref struct")
using System.Collections.Concurrent;
using System.Linq.Expressions;
using System.Reflection;

public static class RefStructReader
{
    static readonly ConcurrentDictionary<PropertyInfo, Func<object, object?>> Cache = new();

    public static object? GetValue(object target, PropertyInfo property)
    {
        if (!property.PropertyType.IsByRefLike)
            return property.GetValue(target);

        return Cache.GetOrAdd(property, Build)(target);
    }

    static Func<object, object?> Build(PropertyInfo property)
    {
        // (object o) => Convert(((TDeclaring)o).Property)
        var arg = Expression.Parameter(typeof(object), "o");
        var read = Expression.Property(Expression.Convert(arg, property.DeclaringType!), property);
        return Expression.Lambda<Func<object, object?>>(Convert(read), arg).Compile();
    }

    // Turns an expression of a ref struct type into an expression of type object
    // without ever boxing the ref struct itself.
    static Expression Convert(Expression refStruct)
    {
        Type type = refStruct.Type;
        if (IsSpan(type))
            return Expression.Convert(Expression.Call(PickConverter(type), refStruct), typeof(object));

        // Unknown ref struct: copy it into a local, then read its public properties one by one.
        var local = Expression.Variable(type, "value");
        var dict = Expression.Variable(typeof(Dictionary<string, object?>), "dict");
        var add = typeof(Dictionary<string, object?>).GetMethod("Add")!;
        var body = new List<Expression>
        {
            Expression.Assign(local, refStruct),
            Expression.Assign(dict, Expression.New(typeof(Dictionary<string, object?>))),
        };
        foreach (PropertyInfo p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            if (p.GetIndexParameters().Length > 0) continue;
            Expression value = Expression.Property(local, p);
            value = p.PropertyType.IsByRefLike ? Convert(value) : Expression.Convert(value, typeof(object));
            body.Add(Expression.Call(dict, add, Expression.Constant(p.Name), value));
        }
        body.Add(Expression.Convert(dict, typeof(object)));
        return Expression.Block(typeof(object), [local, dict], body);
    }

    static bool IsSpan(Type type) =>
        type.IsGenericType &&
        (type.GetGenericTypeDefinition() == typeof(Span<>) || type.GetGenericTypeDefinition() == typeof(ReadOnlySpan<>));

    static MethodInfo PickConverter(Type type)
    {
        if (type == typeof(ReadOnlySpan<char>)) return Method(nameof(FromChars));
        if (type == typeof(Span<char>)) return Method(nameof(FromMutableChars));

        if (type.IsGenericType)
        {
            Type def = type.GetGenericTypeDefinition();
            Type element = type.GetGenericArguments()[0];
            if (def == typeof(ReadOnlySpan<>)) return Method(nameof(FromReadOnlySpan)).MakeGenericMethod(element);
            if (def == typeof(Span<>)) return Method(nameof(FromSpan)).MakeGenericMethod(element);
        }

        throw new NotSupportedException($"No converter for {type}");
    }

    static MethodInfo Method(string name) =>
        typeof(RefStructReader).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static)!;

    static object FromChars(ReadOnlySpan<char> s) => new string(s);
    static object FromMutableChars(Span<char> s) => new string(s);
    static object FromReadOnlySpan<T>(ReadOnlySpan<T> s) => s.ToArray();
    static object FromSpan<T>(Span<T> s) => s.ToArray();
}

The key line is Expression.Call(PickConverter(type), refStruct): the span flows from the getter straight into a converter whose parameter type is the span type, and only the converter’s string or T[] result gets boxed. For ref structs that are not spans, the block expression copies the value into a typed local and reads each public property from it, recursing when a nested property is itself byref-like.

A driver that walks every public property:

// .NET 11.0.0, C# 15
using System.Globalization;
using System.Reflection;
using System.Text.RegularExpressions;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Match match = new Regex(@"\d+").Match("testing 123");
Dump(match);
Dump(new Sensor());

static void Dump(object target)
{
    foreach (PropertyInfo p in target.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
    {
        object? value = RefStructReader.GetValue(target, p);
        string text = value switch
        {
            Array a => $"[{string.Join(", ", a.Cast<object>())}]",
            IDictionary<string, object?> d => "{ " + string.Join(", ", d.Select(kv => $"{kv.Key} = {kv.Value}")) + " }",
            _ => $"{value}",
        };
        Console.WriteLine($"{target.GetType().Name}.{p.Name} ({p.PropertyType.Name}) = {text}");
    }
}

public class Sensor
{
    private readonly double[] _readings = [20.5, 21.0, 21.75];
    public string Id => "s-01";
    public ReadOnlySpan<double> Readings => _readings;
    public Span<byte> Scratch => new byte[] { 1, 2, 3 };
    public Frame Last => new(_readings.Length);
}

public readonly ref struct Frame(int index)
{
    public int Index { get; } = index;
    public ReadOnlySpan<char> Label => "latest";
}

Output from dotnet run on .NET 11.0.0:

Match.Groups (GroupCollection) = System.Text.RegularExpressions.GroupCollection
Match.Success (Boolean) = True
Match.Name (String) = 0
Match.Captures (CaptureCollection) = System.Text.RegularExpressions.CaptureCollection
Match.Index (Int32) = 8
Match.Length (Int32) = 3
Match.Value (String) = 123
Match.ValueSpan (ReadOnlySpan`1) = 123
Sensor.Id (String) = s-01
Sensor.Readings (ReadOnlySpan`1) = [20.5, 21, 21.75]
Sensor.Scratch (Span`1) = [1, 2, 3]
Sensor.Last (Frame) = { Index = 3, Label = latest }

Frame.Label, a ReadOnlySpan<char> nested inside a ref struct, comes out as a string, and nothing threw.

Traps on the way to that reader

The expression interpreter cannot do it

LambdaExpression.Compile(preferInterpretation: true) runs the same tree through the LINQ expression interpreter instead of emitting IL. With a ref struct in the tree it fails before running anything:

ArgumentException: GenericArguments[1], 'System.ReadOnlySpan`1[System.Char]', on
'System.Linq.Expressions.Interpreter.FuncCallInstruction`2[T0,TRet]' violates the constraint of type 'TRet'.

The interpreter’s internal generic instructions are not declared allows ref struct. This is tracked as dotnet/runtime#96160, still open. It matters beyond the explicit flag: on platforms where dynamic code is not supported, such as Native AOT, LINQ expressions are interpreted. That case was not tested for this post, but the interpreter failure above is the same code path, so expect the expression-based reader to fail there. For Native AOT, prefer typed delegates or UnsafeAccessor, or move the work into a source generator that emits typed accessors at build time.

Calling ToString on a ref struct can still box

A tempting shortcut is to emit IL that calls ToString() on the value with a constrained. prefix. That works for ReadOnlySpan<char> because ReadOnlySpan<T> overrides ToString. For a ref struct that does not override it, the constrained call has to fall back to boxing, and the JIT rejects the method when it is first called:

InvalidProgramException: Cannot create boxed ByRef-like values.

C# catches the same thing at compile time. Inside a method with where T : allows ref struct, value.ToString() fails with CS0029: Cannot implicitly convert type 'T' to 'object'. Read the struct’s fields or properties instead, as the reader above does.

Spans of spans do not exist, but spans of anything else do

FromReadOnlySpan<T> relies on MakeGenericMethod(element) where element is the span’s item type. That is always safe: Span<T> and ReadOnlySpan<T> do not allow a ref struct as T, so the element type is always something ToArray() can copy into a normal array. Keep in mind that ToArray() copies. For a large buffer in a hot path, convert lazily or report only the Length.

Indexers and ref returns

The reader skips indexed properties, because Expression.Property needs index arguments. Properties that return by reference (public ref int Foo => ref _x;) are a different case: their PropertyType is System.Int32&, IsByRef is true and IsByRefLike is false, and on .NET 11 GetValue simply dereferences them and returns the boxed int. Only byref-like types need the treatment in this post.

Ref struct fields

Classes cannot declare ref struct fields; only other ref structs can (ref struct Outer { public Span<int> Items; }). Plain FieldInfo.GetValue is a dead end there twice over: the field value cannot be boxed, and neither can the Outer instance you would have to pass as the target. The expression reader already holds the outer value in a typed local, so add a loop over type.GetFields(BindingFlags.Instance | BindingFlags.Public) that uses Expression.Field(local, f) next to the property loop. With that loop added, a class property of type Outer came back as a dictionary holding Items as an int[] and Count as 2.

Which approach to use

You know at compile timeUse
Declaring type and property typeCreateDelegate<Func<TDeclaring, TProp>>() on the getter, cached
Same, but the getter is non-public, or you target Native AOT[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "get_X")] on the declaring type
Only the property typeGeneric GetProperty<T>() where T : allows ref struct, compiled once per property
Nothing, only a PropertyInfoCompiled expression that converts the value to string, T[], or a dictionary inside the tree

If the spans themselves are new territory, what Span is and when it makes code faster and List vs Span vs ReadOnlySpan in C# explain why these types refuse to live on the heap in the first place, which is the whole reason reflection cannot hand them back to you.

Sources

Comments

Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.