Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 658
Sean Missingham Avatar asked Nov 19 '15 07:11

Sean Missingham


3 Answers

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.

like image 72
Jon Skeet Avatar answered Sep 28 '22 02:09

Jon Skeet


Okay so it turns out I'm special. Here's the answer for those that may stumble across this in future,

Turns out you can just use the key like an array index and it works perfectly. So:

File[Key] = Value; Works the way I need as opposed to File.Key = Value;

Thanks anyway!

like image 45
Sean Missingham Avatar answered Sep 28 '22 03:09

Sean Missingham


You can do it, if you're using JObject from JSON.NET. It does not work with an ExpandoObject.

Example:

void Main()
{
    var j = new Newtonsoft.Json.Linq.JObject();
    var key = "myKey";
    var value = "Hello World!";
    j[key] = value;
    Console.WriteLine(j["myKey"]);
}

This simple example prints "Hello World!" as expected. Hence

var File = new Newtonsoft.Json.Linq.JObject();
public void Update(string key, string Value)
{
    File[key] = Value;
}

does what you expect. If you would declare File in the example above as

dynamic File = new ExpandoObject();

you would get a runtime error:

CS0021 Cannot apply indexing with [] to an expression of type 'ExpandoObject'

like image 42
Matt Avatar answered Sep 28 '22 04:09

Matt