Dynamic property name as string
15,567
The System.Dynamic.ExpandoObject
type (which was introduced as part of the DLR) seems close to what you are describing. It can be used both as a dynamic object and as a dictionary (it actually is a dictionary behind the scenes).
Usage as a dynamic object:
dynamic expando = new ExpandoObject();
expando.SomeProperty = "value";
Usage as a dictionary:
IDictionary<string, object> dictionary = expando;
var value = dictionary["SomeProperty"];
Author by
Admin
Updated on June 21, 2022Comments
-
Admin almost 2 years
When creating a new document with DocumentDB, I would like to set the property name dynamically, currently I set
SomeProperty
, like this:await client.CreateDocumentAsync("dbs/db/colls/x/" , new { SomeProperty = "A Value" });
, but I would like to get the
SomeProperty
property name from a string so that I can access different properties using the same line of code, like this:void SetMyProperties() { SetMyProperty("Prop1", "Val 1"); SetMyProperty("Prop2", "Val 2"); } void SetMyProperty(string propertyName, string val) { await client.CreateDocumentAsync("dbs/db/colls/x/" , new { propertyName = val }); }
Is this possible somehow?