2

I'm just curious, in AS3 I can use the methods apply and call, as in:

aFn.apply( thisObj, arrayOfArgs );

or

aFn.call( thisObj, a, b, c );

is there an equivalent syntax in C#?

Preferably without using Reflection.

Thank you for reading.

2
  • 2
    To specify an unknown number of parameters for a method you can use params object[] myObjects syntax for this parameter. msdn.microsoft.com/en-us/library/w5zay9db.aspx Commented Oct 23, 2013 at 16:21
  • @Aybe that would like using the rest parameter from AS3, I get it. Thanks. Commented Oct 23, 2013 at 16:25

1 Answer 1

2

Not quite. Given a particular instance method like say Object#Equals You can use Delegate.CreateDelegate to create an "open" delegate. Which will unbind the "this" parameter. Unfortunately, it will not call that particular implementation of Equals, it will call this's class implementation. As Object#Equals is a virtual method.

Once you have your open delegate you can use dynamic invoke. To apply, but the first element in the array is the this.

You can do this::

var @this = new { a = 3, b = 4 };
var other = new { a = 3, b = 4 };
Func<object, object, bool> equalFn = Delegate.CreateDelegate(
  typeof(Func<object, object, bool>),
  typeof(object).GetMethod("Equals",
    System.Reflection.BindingFlags.Public |
    System.Reflection.BindingFlags.Instance)) as Func<object, object, bool>;
equalFn.Invoke(@this, other); // call example
equalFn.DynamicInvoke(new[] { @this, other }); // apply example

Open delegates are fairly useful. I can't really recommend a good use for DynamicInvoke if you know your types though.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your time. It seems there's no other way than using reflection and DynamicInvoke.
For apply, no there is no alternative without Reflection or emitting code (you could probably write an expression tree to take an array and pass it to the right spots). For call, creating a delegate is slow, but if you keep the delegate it should perform about the same as a virtcall.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.