Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a RuntimeBinderException using json.net with dynamic when calling a method

Why is it that when I use dynamic with json.net I get a runtime binding exception then calling a method without casting but I can do assignments not problem

private static void Main()
{
    dynamic json = JObject.Parse("{\"Test\":23}");
    var t = json.Test;
    int a = t; //Success
    Prop = t; //Success
    Func(t); //RuntimeBinderException
}

private static void Func(int i){}

private static int Prop { get; set; }

When I cast it to the correct type there are no errors but I would prefer to not have to do that. Am I doing something wrong, is this a problem in the json.net library or is a language restriction.

Edit: This is to solve a problem where I don't have control over the methods signature and I don't want to cast it on every call.

like image 988
Glitch Avatar asked Nov 09 '11 15:11

Glitch


1 Answers

This is because json.Test returns a JValue and JValue has a dynamic TryConvert. So if you do an implicit static conversion by pointing it to an int or cast to an int it will at runtime call that TryConvert and you have success. However if you use that dynamically typed variable in a method argument, the c# runtime looks for a method named Func with an argument that best matches 'JValue' it will not try to call 'TryConvert' for every permutation of a possible method (even if it's only one) thus you get the runtime binding error.

So the simplest solution is to just cast on every call or set a statically typed variable each time you want to pass a JValue as an argument.

There is actually a more general question and answer of this same issue too if you are looking for more info: Pass a dynamic variable in a static parameter of a method in C# 4

like image 152
jbtule Avatar answered Oct 12 '22 23:10

jbtule