C # passing a variable number of reference parameters

In C # .NET, is there a way to pass a variable number of objects as reference objects? For example:

MyMethod (ref param1, ref param2, ref param3) 

... with any number of parameters of various types.

+7
source share
2 answers

You can if you want to use the undocumented keywords __arglist and __refvalue in C #.

Caution: Undocumented features may be changed in future versions of C #. Use these keywords only if necessary, realizing that your code may stop working if Microsoft changes its behavior in the next version.

For example, the following program passes three int variables by reference to the GetRandomValues method. It prints 2, 1, and 4, demonstrating that the variables have been successfully changed.

 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); } } 
+6
source

No, this is not possible: a variable number of arguments is implemented as "syntactic sugar" on top of the array transfer; it is impossible to create an array of transfer parameters by reference, because "passed by reference" is not a type property.

+5
source

All Articles