I'm looking for a way to modify properties on a dynamic
C# 4.0 object with the name of the property known only at runtime.
Is there a way to do something like (ExpandoObject
is just used as an example, this could be any class that implements IDynamicMetaObjectProvider
):
string key = "TestKey";
dynamic e = new ExpandoObject();
e[key] = "value";
Which would be equivalent to:
dynamic e = new ExpandoObject();
e.TestKey = "value";
Or is the only way forward reflection?
Paul Sasik answered a similar question at C# 4.0 Dynamic vs Expando... where do they fit?
fast-member may fit the bill - it looks like it generates the IL on the fly, but caches it so it's really fast after the first use.
My open source framework Dynamitey has methods for invoking based on string names using the DLR. It does the work of caching binding sites and streamlines it down to one method call. it also runs faster than reflection on non-dynamic objects too.
To add to Jonas' answer, you don't have to create a new var p. Use this approach instead:
Not very easily, no. Reflection doesn't work, since it assumes a regular type model, which is not the full range of
dynamic
. If you are actually just talking to regular objects, then just use reflection here. Otherwise, I expect you may want to reverse-engineer the code that the compiler emits for a basic assignment, and tweak it to have a flexibly member-name. I'll be honest, though: this isn't an attractive option; a simple:translates to:
If you want an approach that works for both dynamic and non-dynamic objects: FastMember is handy for this, and works at either the type or object level:
available on Nuget, and heavily optimised for both dynamic and non-dynamic scenarios.