Is there a way to pass by reference using variable parameters in C #?

I would like to have a function that modifies a list of variables, but all types of values ​​(int, string). Is there a way to get the params keyword to work with the ref keyword or something close to that?

public void funcParams(params object[] list) { /* Make something here to change 'a', 'b' and 'c' */ } public void testParams() { int a = 1, b = 2, c = 3; funcParams(a, b, c); } 

The problem is that I am trying to simplify my life by creating a method that changes the fields of an object. I am doing dynamic code generation with Cecil, and I try to avoid writing too much code generated by IL.

To simplify, I would like to pass the list of fields by reference, I need to go to a function that changes them, rather than changing them, generating the corresponding IL. Some of the parameters are nullable and make code generation a bit more painful. In this case, using some overload methods instead of parameters will not be very useful.

+4
source share
3 answers

Yes. Maybe.

However, the resulting code is "unsafe", which makes it invalid.

This may or may not be a problem depending on your requirements.

Anyway, here is the code:

 using System; namespace unsafeTest { class MainClass { public static void Main(string[] args) { Console.WriteLine("Hello World!"); unsafe { int x = 0; int y = 0; int z = 0; bar(&x, &y, &z); Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } } unsafe static void bar(params int *[] pInts) { int i = 0; foreach (var pInt in pInts) { *pInt = i++; } } } } 
+5
source

Well, you can declare several overloads, i.e.

 public void FuncParams(ref int a) {...} public void FuncParams(ref int a, ref int b) {...} 

etc.

Otherwise, you have to read back from the array (since params really means "implicit array"):

 object[] args = {1,2,3}; funcParams(args); Console.WriteLine(args[0]); // updated Console.WriteLine(args[1]); // updated Console.WriteLine(args[2]); // updated 

(of course, if it accepts only int s, it would be better to use int[] )

+8
source

No, this is not possible with neat syntax. The reason is that internally, the runtime considers the method as a simple method that takes an array argument. The compiler controls the creation of the array and populates it with the specified arguments. Since arguments are value types, they will be copied to the array, and any change to them will not affect the original variables. Other ways of doing it will defeat the goal of params , which is a good syntax for a variable number of arguments.

+2
source

All Articles