This comes from this question really: Looping through JSON array and adding items to list C# .

To not derail that question completely, I ask a new one that I started to wonder about.

Using Json.net, why does this code work:

dynamic test = new JValue("test");
string s = test;

while this:

dynamic test = new JValue("test");
var list = new List<string>();
list.Add(test);

throws:

RuntimeBinderException: The best overloaded method match for 'System.Collections.Generic.List<string>.Add(string)' has some invalid arguments

Given that there is just one overload for the Add method, and it takes a string, why won't it silently do the runtime conversion here as well?

Note that there is nothing specific about list.Add that makes this fail, this also fails:

dynamic test = new JValue("test");
Test(test);

...

public static void Test(string s) { }

First thing I could think of was that JValue has an implicit cast operator to string, but alas:

JValue test = new JValue("test");
string s = test;

does not compile, with:

CS0266 Cannot implicitly convert type 'Newtonsoft.Json.Linq.JValue' to 'string'. An explicit conversion exists (are you missing a cast?)

but it does say an explicit conversion exists, is this what "saves" the direct assignment to a string variable? But then, still, why didn't it save the usage as a parameter value where the only available overload takes a string parameter? Does assignment have extra rules perhaps?


After having thought some more about this I guess this question is actually the wrong question.

dynamic is not supposed to make more things work at runtime than they would at compile time, instead it's just meant to postpone the type binding to runtime.

So changing the type of the variable to a statically typed one, and neither of the examples work:

JValue test = new JValue("test");
string s = test; // CS0266 Cannot implicitly convert type 'Newtonsoft.Json.Linq.JValue' to 'string'. An explicit conversion exists (are you missing a cast?)

JValue test = new JValue("test");
Test(test); // same
0

There are 0 answers