How to set a property of a C# 4 dynamic object when you have the name in another variable

Posted by Kieran Benton on Stack Overflow See other posts from Stack Overflow or by Kieran Benton
Published on 2010-06-13T18:33:22Z Indexed on 2010/06/13 18:42 UTC
Read the original article Hit count: 246

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET