Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke varargs method

How can I invoke a varargs method using reflection? Like this one:

public static void ArgsMethod(__arglist)
{
    ArgIterator ai = new ArgIterator(__arglist);
    while(ai.GetRemainingCount() > 0)
    {
        Console.WriteLine(TypedReference.ToObject(ai.GetNextArg()));
    }
}

typeof(Program).GetMethod("ArgsMethod").Invoke(null,new object[0]) throws NotSupportedException.

like image 556
IS4 Avatar asked Oct 17 '25 00:10

IS4


1 Answers

Since RuntimeMethodInfo simply doesn't support this (it explicitly checks and throws if the calling convention of the method is VarArgs), you'll have to write a wrapper that takes a regular Object[], generates IL for calling the method, and invokes that. ILGenerator does support varargs-methods through EmitCall. The MSDN is even helpful enough to have a sample that demonstrates this exact scenario.

Of course, it's not exactly convenient, but then nothing about varargs is, really.

like image 195
Jeroen Mostert Avatar answered Oct 18 '25 14:10

Jeroen Mostert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!