user152949
user152949

Reputation:

Dynamic property name as string

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?

Upvotes: 8

Views: 25788

Answers (1)

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29213

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"];

Upvotes: 13

Related Questions