C# passing a variable number of reference parameters
c#, parameters
Solution
You can, if you're willing to use the undocumented `__arglist` and `__refvalue` keywords in C#.
Caution: Undocumented features are subject to change in future versions of C#. Use these keywords only if you have to, understanding that your code may stop working if Microsoft changes their behavior in the next version.
For example, the following program passes three `int` variables by reference to the `GetRandomValues` method. It outputs 2, 1, and 4, demonstrating that the variables were successfully modified.
static void Main()
{
int x = 0, y = 0, z = 0;
GetRandomValues(__arglist(ref x, ref y, ref z));
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
}
static void GetRandomValues(__arglist)
{
Random random = new Random(1);
ArgIterator iterator = new ArgIterator(__arglist);
while (iterator.GetRemainingCount() > 0)
{
TypedReference r = iterator.GetNextArg();
__refvalue(r, int) = random.Next(0, 10);
}
}
Problem
In C#.NET, is there a way to pass a variable number of objects as reference objects? For instance: ``` MyMethod (ref param1, ref param2, ref param3) ``` ...with any number of parameters, of various types.