DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

How allows ref struct decompiles in .NET

Most C# language features leave a trail in the instruction stream. An async method becomes a state machine you can single-step; a yield return becomes a MoveNext with a jumped-to label; even a using is just a try/finally around a Dispose. A decompiler earns its keep by reading those instructions and folding them back into the syntax that produced them.

The C# 13 allows ref struct anti-constraint is the opposite kind of feature. It produces no method-body IL whatsoever. The entire feature is one bit in one metadata table, set on one generic parameter. That makes it one of the cleanest case studies there is for why a decompiler has to read metadata as carefully as it reads code — because here the code says nothing, and a tool that only reads code will hand you source that compiles, runs identically, and is quietly wrong. This post walks the construct for Glass.NET, the free .NET decompiler.

An anti-constraint, not a constraint

A normal generic constraint adds a requirement. where T : IDisposable says a type argument must implement IDisposable; the compiler enforces it, and the metadata records it as a row in the GenericParamConstraints table pointing at the IDisposable type.

allows ref struct does the reverse. Every generic parameter in .NET carries an invisible, long-standing requirement that its type argument must not be a ref struct (Span<T>, ReadOnlySpan<T>, or any ref struct you declare). That rule existed because ref structs have stack-only lifetime guarantees the generics system historically could not honor. C# 13 and .NET 9 let you lift that rule, per parameter, by writing allows ref struct. You are not adding a requirement — you are removing a prohibition. That is why it is called an anti-constraint, and why it is stored as a permission bit rather than a constraint row.

The C# and the IL it compiles to

Here is a small, realistic use: a pipeline that accepts any parser — including a ref struct parser that wraps a Span<char> — as long as it implements an interface.

using System;

public interface ILineParser
{
    int Parse(ReadOnlySpan<char> line);
}

public static class Pipeline
{
    public static int Run<TParser>(TParser parser, ReadOnlySpan<char> input)
        where TParser : ILineParser, allows ref struct
    {
        return parser.Parse(input);
    }
}
Enter fullscreen mode Exit fullscreen mode

The constraint list reads ILineParser, allows ref struct: a real interface constraint, then the anti-constraint. The interface constraint lets the body call parser.Parse(...); the anti-constraint is what lets a caller later write Run<MySpanParser>(...) where MySpanParser is a ref struct that implements ILineParser — itself a companion C# 13 feature.

Now the IL for Run. The body is an ordinary constrained interface call:

.method public hidebysig static int32
        Run<byreflike (class ILineParser) TParser>(
            !!TParser parser,
            valuetype [System.Runtime]System.ReadOnlySpan`1<char> input) cil managed
{
  .maxstack  2
  ldarga.s   parser
  ldarg.1
  constrained. !!TParser
  callvirt   instance int32 ILineParser::Parse(
                 valuetype [System.Runtime]System.ReadOnlySpan`1<char>)
  ret
}
Enter fullscreen mode Exit fullscreen mode

Read the body and nothing is unusual: load the receiver's address, load the argument, constrained. callvirt the interface method. That is the identical instruction sequence you would get for where TParser : ILineParser with no anti-constraint at all. The only trace of the feature is in the method's signature line — the byreflike keyword on the generic parameter TParser — and byreflike is not an instruction. It is ILAsm's rendering of a flag.

One bit in GenericParameterAttributes

Every generic parameter has a GenericParameterAttributes value — a small bitfield that already encoded variance (out/in) and the special constraints class, struct, and new(). .NET 9 added one more flag to it:

// System.Reflection.GenericParameterAttributes
None                       = 0x0000,
Covariant                  = 0x0001,
Contravariant              = 0x0002,
ReferenceTypeConstraint    = 0x0004,  // where T : class
NotNullableValueTypeConstraint = 0x0008,  // where T : struct
DefaultConstructorConstraint   = 0x0010,  // where T : new()
AllowByRefLike             = 0x0020,  // where T : allows ref struct  (new in .NET 9)
Enter fullscreen mode Exit fullscreen mode

For the Run example, TParser's GenericParameterAttributes is exactly 0x0020: AllowByRefLike set, everything else clear. The ILineParser requirement is not in this value — it is a separate GenericParamConstraints row. You can confirm the split with reflection:

var tp = typeof(Pipeline).GetMethod("Run")!.GetGenericArguments()[0];

tp.GenericParameterAttributes.HasFlag(GenericParameterAttributes.AllowByRefLike); // True
tp.GetGenericParameterConstraints();  // [ ILineParser ] — the interface, nothing about ref struct
Enter fullscreen mode Exit fullscreen mode

The anti-constraint is the one, the interface is the other, and they come from two different tables. A decompiler has to read both and recombine them in the order C# demands: real type constraints first, then allows ref struct last.

Why the identical body is a trap

This is the part that makes the construct worth a whole post. Because the body IL carries no trace of the feature, a decompiler built only to reconstruct instructions will produce a Run method that compiles and runs perfectly — and whose signature forbids the very ref-struct arguments the original allowed. Nothing throws. Nothing looks wrong. The method simply lost a capability that lived entirely in metadata.

Concretely: given the original assembly, Run<MySpanParser>(parser, text) — with MySpanParser a ref struct implementing ILineParser — is legal. Decompile with the anti-constraint dropped, recompile, and that same call site stops compiling with "MySpanParser must be a non-ref-struct type to be used as parameter TParser". For anyone decompiling to understand their own library, diff two builds, or re-target code they are entitled to, that is a silent narrowing of the contract — the kind of regression that is expensive to notice because the code that changed is the code that didn't change.

What Glass.NET reconstructs

Glass.NET reads the generic parameter's flags, not just its body, so the anti-constraint survives the round trip. Point it at the type:

glass decompile Pipeline.dll --type Pipeline --member Run
Enter fullscreen mode Exit fullscreen mode
public static int Run<TParser>(TParser parser, ReadOnlySpan<char> input)
    where TParser : ILineParser, allows ref struct
{
    return parser.Parse(input);
}
Enter fullscreen mode Exit fullscreen mode

The interface constraint and the anti-constraint come back in the correct order, and the body folds the constrained. callvirt back into parser.Parse(input). To see the metadata Glass read to get there, ask it to show its work:

glass decompile Pipeline.dll --type Pipeline --member Run --constraint-check
Enter fullscreen mode Exit fullscreen mode
TParser
  GenericParameterAttributes = 0x0020  (AllowByRefLike)
  GenericParamConstraints:
    [0] ILineParser   (interface)
  => where TParser : ILineParser, allows ref struct
Enter fullscreen mode Exit fullscreen mode

That output puts the raw 0x0020 next to the generated clause, so you can verify the bit is the anti-constraint and not, say, a misread value-type flag. Add --il to confirm the other half of the story — that the body below the signature is an ordinary constrained interface call with nothing feature-specific in it:

glass decompile Pipeline.dll --type Pipeline --member Run --il
Enter fullscreen mode Exit fullscreen mode

The IL pane shows byreflike on the parameter in the .method signature line and the plain constrained. callvirt sequence underneath. In the Avalonia UI the same split is visible at a glance: the generic parameter node under Run lists its decoded flags, and the synced IL view highlights the signature keyword while the body carries no trace of the feature. If you are inspecting a dependency from an AI assistant, the MCP server exposes the same reconstruction — glass mcp lets the assistant call glass_decompile and read the allows ref struct clause itself, all static, read-only inspection with nothing executed.

The takeaway

allows ref struct is the rare feature with zero executable footprint. The compiler expresses it as a single bit — AllowByRefLike, 0x20 — on a generic parameter, and leaves the method body exactly as it would be without it. That is precisely why reading bodies is not enough: the faithful source lives in the metadata, and a tool that ignores the flag will hand you code that compiles, runs the same, and quietly refuses the ref-struct arguments the author deliberately allowed. Reading that one bit back, and placing the clause in the right spot in the constraint list, is the whole job — and it is the difference between source that looks right and source that is right.

Glass.NET is a free .NET decompiler with a Visual-Studio-native Avalonia UI, a CLI, and an MCP server. Download it and read the metadata your compiler left behind.

Top comments (0)