references.md

July 4, 2026 · View on GitHub

Apache Fory™ C# can preserve shared and circular references when TrackRef(true) is enabled.

Enable Reference Tracking

Fory fory = Fory.Builder()
    .TrackRef(true)
    .Build();

When enabled:

  • Shared object identity is preserved.
  • Circular object graphs can be serialized/deserialized safely.

Circular Reference Example

using Apache.Fory;

[ForyStruct]
public sealed class Node
{
    public int Value { get; set; }
    public Node? Next { get; set; }
}

Fory fory = Fory.Builder()
    .TrackRef(true)
    .Build();
fory.Register<Node>(200);

Node node = new() { Value = 7 };
node.Next = node;

byte[] payload = fory.Serialize(node);
Node decoded = fory.Deserialize<Node>(payload);

// The cycle is preserved.
System.Diagnostics.Debug.Assert(object.ReferenceEquals(decoded, decoded.Next));

When to Use TrackRef(false)

TrackRef(false) can be faster for tree-like, acyclic data where reference identity does not matter.

C# union wrappers are immutable and are created after their case payload is read. Reference cycles from a union case payload back to the containing union are not supported; Fory rejects unresolved refs instead of returning a partial union.