Referring to dynamic members of C# 'dynamic' object

I'm using JSON.NET to deserialize a JSON file to a dynamic object in C#.

Inside a method, I would like to pass in a string and refer to that specified attribute in the dynamic object.

For example:

public void Update(string Key, string Value)
    {
        File.Key = Value;
    }

Where File is the dynamic object, and Key is the string that gets passed in. Say I'd like to pass in the key "foo" and a value of "bar", I would do: Update("foo", "bar");, however due to the nature of the dynamic object type, this results in

{
 "Key":"bar"
}

As opposed to:

{
 "foo":"bar"
}

Is it possible to do what I'm asking here with the dynamic object?

Jon Skeet
people
quotationmark

I suspect you could use:

public void Update(string key, string Value)
{
    File[key] = Value;
}

That depends on how the dynamic object implements indexing, but if this is a Json.NET JObject or similar, I'd expect that to work. It's important to understand that it's not guaranteed to work for general dynamic expressions though.

If you only ever actually need this sort of operation (at least within the class) you might consider using JObject as the field type, and then just exposing it as dynamic when you need to.

people

See more on this question at Stackoverflow