1

I am implementing a DynamicObject. In the TryInvokeMethod, in addition to the arguments ( passed in to the method), I also need the names for the parameters if they have been used.

I can see that binder.CallInfo.ArgumentNames does indeed provides the names, but I am not able to associate them with the values. Is there any way to do so, or am I hoping against hope:

public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
    var names = binder.CallInfo.ArgumentNames;
    foreach (var arg in args)
    {
        arguments.Add(new Argument(arg));
    }
    //I need to associate the names and the args
    result = this;
    return true;
}

So for example if I do a call like:

myDynamicObject.DynamicInvoke("test", something: "test2")

I have test and test2, and also something, but I am not able to get the information that something was the name for test2 and test had no name.

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • 2
    You should assume that the last argument name if any corresponds to last method parameter and so on. – user629926 Nov 13 '12 at 18:53
  • @user629926 thanks for the pointer. I used that to get the code below. You can still add as answer if you want and I will accept that. – manojlds Nov 13 '12 at 19:10

1 Answers1

3

I had to use the fact that named arguments occur only after the non-named ones are specified ( thanks to user629926 for pointing to the obvious) and initial code:

var names = binder.CallInfo.ArgumentNames;
var numberOfArguments = binder.CallInfo.ArgumentCount;
var numberOfNames = names.Count;

var allNames = Enumerable.Repeat<string>(null, numberOfArguments - numberOfNames).Concat(names);
arguments.AddRange(allNames.Zip(args, (flag, value) => new Argument(flag, value)));
Community
  • 1
  • 1
manojlds
  • 290,304
  • 63
  • 469
  • 417
  • One option to possibly simplify your code would be to use `var allNames = Enumerable.Repeat(null, numberOfArguments - numberOfNames).Concat(names);`. Then you can just use `Enumerable.Zip` to pair the values and the names, with `null` for unnamed arguments. – Jon Skeet Nov 14 '12 at 15:08
  • @JonSkeet Ah nice. I did refactor the code above, but this is neater. – manojlds Nov 14 '12 at 17:41