DynamicData

MonoMod.Utils.DynamicData gives you name-based access to the fields, properties and methods of an object or type, including private ones, using fast generated accessors instead of plain reflection. It can also attach extra data to existing objects. It works both through explicit methods (Get, Set, Invoke) and through C# dynamic. This page documents its API, lookup order, and lifetime rules.

Quick Example

using MonoMod.Utils;

var player = new Player();

// Explicit API
var data = new DynamicData(player);
int secret = data.Get<int>("secretCounter");    // private field
data.Set("secretCounter", secret + 1);
data.Invoke("RecalculateStats");                // private method

// Extra per-object data (no such member exists on Player)
data.Set("MyMod_LastHitTime", DateTime.Now);

// dynamic API
dynamic d = new DynamicData(player);
d.secretCounter = 5;
d.RecalculateStats();
Player back = d;    // converts to the target object

Creating a DynamicData

Constructor / factory Target Keeps the target alive?
new DynamicData(object obj) obj, members of obj.GetType() Yes
new DynamicData(Type type, object? obj) obj, members of type (useful to see a base type's members) Yes
new DynamicData(Type type, object? obj, bool keepAlive) as above Only if keepAlive
new DynamicData(Type type) Static members of type (no target)
DynamicData.For(object obj) A cached instance per object, stored in a ConditionalWeakTable Yes, while that cached instance exists

When obj is null, the instance works on static members of type.

DynamicData holds the target through a WeakReference. With keepAlive (the default for the object constructors) it also holds a strong reference until Dispose() is called. IsAlive reports whether the target still exists; Target returns it (or null); TargetType is the type whose members are used.

Member Lookup

On first use for a type, DynamicData builds a cache by walking the type and all its base types, collecting public and non-public, instance and static members:

  • Fields: a getter and a setter (constants get only a getter). The most-derived field wins when names repeat.
  • Properties: a getter and/or setter for each accessor that exists.
  • Methods: one invoker per name. A name that is overloaded in the same type is skipped (it is ambiguous), and generic methods are skipped.

Fast invokers are created with GetFastInvoker(); if that fails for a member, MonoMod logs a warning and falls back to reflection for it.

Get, Set and Invoke

Method Lookup order When the name is unknown
Get(name), Get<T>(name), TryGet(name, out value), TryGet<T>(...) Registered getters → cached member getters → extra data Get returns null; TryGet returns false.
Set(name, value) Registered setters → cached member setters → extra data The value is stored as extra data under that name.
Invoke(name, params args), Invoke<T>(...), TryInvoke(...) Registered methods → cached methods Invoke returns null; TryInvoke returns false.

Get<T>/Invoke<T> cast the result with (T?), so a wrong type throws InvalidCastException.

Warning: Because unknown names fall through to the extra-data store, a typo in a member name does not throw. Set("helth", 10) silently creates extra data instead of setting health, and Get("helth") then returns that value. Use TryGet/TryInvoke or check Getters/Methods when you need to be sure a real member was found.

Registering Virtual Members

Method Effect
RegisterProperty(name, getter, setter) Adds a virtual property for this object's data (Func<object?, object?> getter, Action<object?, object?> setter, both receiving the target).
UnregisterProperty(name) Removes it.
RegisterMethod(name, Func<object?, object?[]?, object?> cb) Adds a virtual method.
UnregisterMethod(name) Removes it.

The Getters, Setters, Methods and Data dictionaries expose these per-object registrations directly. They are shared by every DynamicData for the same target object (or the same type, for static access).

Extra Data Lifetime

Extra data and registrations are stored per target object in a ConditionalWeakTable, so they live exactly as long as the target object, no matter how many DynamicData wrappers you create or dispose. For static access (obj == null), they are stored per Type.

Static Helpers

Method Description
DynamicData.Wrap(object target, object? other = null) Returns a new DynamicData as dynamic, after copying other's public properties onto it.
DynamicData.Set(object target, object? other = null) / Set<T>(...) Copies other's public instance properties onto target (via For(target)) and returns the target. Works well with anonymous objects: DynamicData.Set(player, new { health = 50, secretCounter = 0 }).
DynamicData.New<T>(params object[] args) / New(Type, params object[]) Creates an instance (non-public constructors allowed) and returns a function that applies Set with a given object.
DynamicData.NewWrap<T>(...) / NewWrap(Type, ...) Same, but the function returns the dynamic wrapper.
CopyFrom(object? other) Instance version of the property copy.
event OnInitialize Action<DynamicData, Type, object?> raised at the end of every constructor, so mods can register virtual members globally.

dynamic Support

DynamicData derives from DynamicObject:

  • Member get/set map to Get/Set. Getting a name that is a registered method returns no value (the binder fails), so call it instead.
  • Method calls map to TryInvoke.
  • Conversions to the target type (or a compatible type, or object) return the target; conversion to DynamicData returns the wrapper itself.
  • GetDynamicMemberNames() and the IEnumerable<KeyValuePair<string, object?>> implementation list every known name.

DynData (Legacy)

DynData<TTarget> (DynData.cs) is the older, generic predecessor and is still present. Prefer DynamicData in new code.

See Also