ObjectTreeWalker 0.12.6

dotnet add package ObjectTreeWalker --version 0.12.6
                    
NuGet\Install-Package ObjectTreeWalker -Version 0.12.6
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ObjectTreeWalker" Version="0.12.6" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ObjectTreeWalker" Version="0.12.6" />
                    
Directory.Packages.props
<PackageReference Include="ObjectTreeWalker" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ObjectTreeWalker --version 0.12.6
                    
#r "nuget: ObjectTreeWalker, 0.12.6"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ObjectTreeWalker@0.12.6
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ObjectTreeWalker&version=0.12.6
                    
Install as a Cake Addin
#tool nuget:?package=ObjectTreeWalker&version=0.12.6
                    
Install as a Cake Tool

Build & Test

ObjectGraphWalker

ObjectGraphWalker is a powerful utility library that enables seamless traversal over C# object properties and fields, Node.js style. Designed with performance and flexibility in mind, it leverages dynamic code generation and caching to provide efficient traversal capabilities.

Features

  • Fast Traversal: Utilizes dynamic code generation to create accessors that speed up traversal.
  • Flexible Filtering: Allows custom predicates to include or exclude specific members during traversal.
  • Support for Various Types: Works with both value and reference types, including generics and embedded structs.
  • Deep Cloning: Includes a high-performance deep clone extension method for complex object graphs.
  • Well-Tested: Includes comprehensive tests to ensure reliability and correctness.

Installation

Simply install the NuGet Package

Usage Examples

Simple Example

A basic example that demonstrates how to traverse an object and access its properties:

var someObject = new SomeObject();
var iterator = new ObjectMemberIterator();
iterator.Traverse(someObject, (in MemberAccessor accessor) =>
{
    var propertyValue = accessor.GetValue();
    accessor.SetValue(/* some other value */);
});

Advanced Example

An advanced example that shows how to use predicates to filter members and control the traversal behavior:

var someObject = new SomeObject();
var iterator = new ObjectMemberIterator();
iterator.Traverse(someObject, (in MemberAccessor accessor) =>
{
    var propertyValue = accessor.GetValue();
    accessor.SetValue(/* some other value */);

    //filtering for selective iteration is a simple lambda
}, (in MemberAccessor accessor) => accessor.Name != "Foo1" && accessor.MemberType != MemberType.Property);

Deep Cloning

You can easily create deep clones of any object using the provided extension method:

var someObject = new SomeObject();
var clone = someObject.DeepClone();

Performance

DeepClone() is benchmarked against AnyClone and DeepCloner using BenchmarkDotNet (dotnet run -c Release --project bench/DeepCloneBenchmark). Graph100 is a list of 100 complex objects (each with a nested object, a 16-item List<int> and a 2-entry Dictionary<string, SimpleObject>), every 10th one shared:

Scenario ObjectTreeWalker DeepCloner AnyClone
Simple object 13.9 ns / 32 B 99.9 ns / 168 B 1,318.8 ns / 2,624 B
Complex object 278 ns / 448 B 1,084 ns / 1,496 B 11,277 ns / 17,000 B
Graph100 26.2 µs / 44.8 KB 95.0 µs / 127.0 KB 1,352.6 µs / 1,943.5 KB

Traversal (dotnet run -c Release --project bench/IteratorBenchmark): a 2-member object in 89 ns / 24 B, the complex object in 1.04 µs / 936 B.

(Intel Xeon @ 2.10GHz, 4 cores, .NET 10.0, 2 launches x 15 iterations - actual numbers will vary by machine.)

How

  • No reflection on the hot path, no dependencies. Every per-type cloner and member accessor is hand-written IL (System.Reflection.Emit), built once per type.
  • Dispatch resolved at JIT time. Per-type cloners live in generic static caches (Cloner<T>), and the emitted IL calls the cloner of each field's static type directly; a runtime type check routes subclasses and interface-typed fields through dynamic dispatch. Whether a type needs cloning at all is a static readonly bool the JIT folds into a constant, so strings and reference-free structs cost nothing.
  • No MemberwiseClone, no Array.Clone. On .NET 10 they measured 4-5x slower than allocating uninitialized and copying typed fields (or a span memmove) for typical objects; they are used only for wide or explicit-layout types.
  • Typed collection paths. T[], List<T>, Dictionary<K,V> and HashSet<T> are cloned with typed code (no boxing, no non-generic enumerators). When keys need no cloning, a dictionary's hash structure is copied verbatim and only values are replaced in place - no re-hashing. This relies on the BCL's private layout, so it is enabled only after verifying that layout, and falls back to the public API otherwise.
  • A purpose-built identity map (open addressing, single probe per object, O(used) reset, pooled per thread) tracks shared references and cycles.

Notes

  • The iterator reads public and private properties and fields, including private members declared on base classes, but ignores static members. A member hidden with new is reported separately from the member it hides; an overridden property is reported once.
  • The iterator will ignore backing fields for "auto properties" and any compiler-generated fields such as closures (unless specified in the constructor). Pointer, by-ref and ref struct members are skipped.
  • Traversal contract: collection members are expanded, never visited; collection items are reported as MemberType.CollectionItem and are read-only (SetValue on one throws InvalidOperationException); dictionary keys/values are flagged IsPartOfDictionary; an already-expanded instance (object or collection) reached again is reported once as a leaf and never re-expanded, so cyclic graphs - including a collection containing itself - terminate; struct TContext accumulates across collection recursion; a root string or other member-less leaf visits zero members.
  • PropertyPath is the full route to a member, through collection items too (Items[0], V for Items[0].V).
  • SetValue persists changes made to members of structs: the modified copy is written back through every enclosing struct and into the enclosing list, array or dictionary value. When that is impossible it throws InvalidOperationException instead of silently losing the change (a struct in a HashSet<T> or a dictionary key, a struct reached through a get-only property, a get-only property itself).
  • KeyValuePair<K,V> members report Key/Value once; multidimensional array items use rank indices (M[0,1]); enum members are leaves.
  • By default a throwing member getter aborts the whole traversal; pass skipThrowingMembers: true to the ObjectMemberIterator constructor to skip such members instead.
  • DeepClone() supports arrays, dictionaries, IList/ICollection<T> collections, concurrent collections and plain objects, including private fields of base classes. Collections without a usable constructor (ReadOnlyCollection<T>, ImmutableArray<T>, ...) are cloned field by field. Reflection objects (Type, MemberInfo, ...) are shared, never copied. Compiler-generated iterator state machines (e.g. yield generators) throw NotSupportedException — materialize them into a List<T> or array first. Collection comparers are preserved when the type offers a matching constructor.
  • Long-lived hosts that see many dynamic or generic types can reclaim type-cache memory via ObjectMemberIterator.ClearCache() and ObjectExtensions.ClearCache(). The compiled per-type cloners themselves live in generic static caches for the process lifetime (like EqualityComparer<T>.Default).
  • While the iterator is well-tested, there may be some bugs. If you encounter any issues, please open an issue with a description.

Contributing

Any contributions are welcome 😃

License

MIT License

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.1

    • No dependencies.
  • net10.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on ObjectTreeWalker:

Package Downloads
IteratorBenchmark

Package Description

DeepCloneBenchmark

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.12.6 98 11/17/2026
0.12.5 171 9/26/2026
0.12.3 227 3/16/2026
0.12.2 173 3/16/2026
0.11.1 608 4/25/2024
0.11.0 316 4/25/2024
0.10.18 908 8/21/2023
0.10.14 314 7/6/2023
0.10.13 388 5/27/2023
0.10.11 419 4/4/2023
0.10.8 636 1/14/2023
0.10.7 495 1/14/2023
0.10.5 493 12/25/2022
0.10.4 488 12/24/2022
0.10.3 2,251 12/3/2022
0.10.2 536 12/3/2022
0.9.4 512 11/29/2022
0.9.3 496 11/29/2022
0.9.2 688 11/7/2022
0.9.1 654 10/20/2022
Loading failed

Changes since version v1.0.10.0

Fixed:
- Traversal of a collection that (directly or through its items) contains itself no longer loops forever with an ever-growing queue: collections are tracked like any other visited instance.
- Collection items of a nested type (e.g. an enum or class declared inside another class) reported as leaves no longer throw `ArgumentException`.
- The shared type-graph cache is now keyed by all enumerator settings; a traversal can no longer make a later `DeepClone` of a `KeyValuePair<K,V>` shallow.
- Private fields declared on base classes are now traversed and deep cloned (they were silently skipped, so clones shared that state with the source).
- `DeepClone` of `Stack<T>`, `Queue<T>`, `ConcurrentBag<T>` and other collections reaching the field-wise path now clones their storage; it used to be a shallow `MemberwiseClone` (a cloned `ConcurrentBag<T>` shared its items with the source).
- `DeepClone` of collections without a usable constructor (`ReadOnlyCollection<T>`, `ReadOnlyDictionary<K,V>`, `ImmutableArray<T>`, ...) clones them field by field instead of throwing.
- `DeepClone` no longer copies reflection objects (`Type`, `MemberInfo`, ...) - a copied `RuntimeType` is a distinct, broken `Type`.
- Members hidden with `new` (with a different type) no longer crash the accessor with a duplicate key, and are read/written independently of the member they hide.
- `MemberAccessor.SetValue` persists changes to members of structs at any nesting depth, and to members of struct items in lists, arrays and dictionary values; it throws when the change cannot be persisted, and on get-only properties, instead of silently doing nothing.
- `PropertyPath` of members inside collection items now includes the path to the item (it used to restart at the item).
- Single-dimension arrays with a non-zero lower bound are traversed correctly.
- Pointer, by-ref and `ref struct` members are skipped instead of making the whole type unsupported.
- The netstandard2.1 build now rejects ref structs in `ObjectAccessor` like the net10.0 build (the check was compiled only for .NET 8+).

Changed:
- `DeepClone` rewritten around per-type cloners in hand-written IL held in generic static caches, typed collection paths and a purpose-built identity map: 3-5x faster than before and 3.4-7x faster than DeepCloner on the included benchmarks, with fewer allocations (see README).
- Traversal: 2-2.6x faster and 82-94% fewer allocations - type-keyed graph cache (no record hashing per value), monomorphic inline caches per member, cached item names, property paths built on demand, pooled identity map, no per-call closures.
- No package dependencies: Sigil (and its IL verifier) replaced by plain `System.Reflection.Emit`.
- Member reads/writes during traversal call compiled delegates bound to the member, instead of a name-keyed lookup on every access.
- Dropped the `Microsoft.Extensions.ObjectPool` and `System.Memory` dependencies; package versions are pinned instead of floating (`*`).
- `MemberAccessor.SetValue` accepts `null` (`object?`); null sets a value-type member to its default.
- Traversal no longer double-visits `KeyValuePair<K,V>` members (reports `Key`/`Value` once).
- Multidimensional array items now use rank indices (`M[0,1]`) instead of a flat position.
- Enum members are leaves (no more `value__` expansion), matching `DeepClone`.
- `DeepClone` of compiler-generated iterator state machines now throws `NotSupportedException` instead of producing a field-wise copy.
- `DeepClone` no longer copies framework collection internals (e.g. `ConcurrentDictionary` locks) and preserves extra state declared on intermediate bases (`A : B : List<int>`).
- `DeepClone` keeps the source comparer for collections without a pre-sizing constructor (e.g. `SortedSet<T>`).
- `MemberAccessor.SetValue` on a collection item now throws `InvalidOperationException` instead of silently ignoring the set.

Added:
- `ObjectMemberIterator(skipThrowingMembers: true)` skips members whose predicate or getter throws instead of aborting traversal.
- `ObjectMemberIterator.ClearCache()` and `ObjectExtensions.ClearCache()` for reclaiming type-cache memory in long-lived hosts; oversized pooled traversal queues are dropped instead of retained.