Pass infinite params by reference (using keywords params and ref together)

178 Views Asked by At

Is it possible to pass an infinite number of parameters into my function by reference?

I know this is not valid, but is there a way to do this?

private bool Test(ref params object[] differentStructures)
{
    //Change array here and reflect changes per ref
}

TestStructOne test1 = default(TestStructOne);
TestStructTwo test2 = default(TestStructTwo);
TestStructOne test3 = default(TestStructOne);
if (Test(test1, test2, test3)) { //happy dance }

I know I could do the following, but I'm hoping to eliminate having to create an extra variable to contain all the objects...

private bool Test(ref object[] differentStructures)
{
    //Change array here and reflect changes per ref
}

TestStructOne test1 = default(TestStructOne);
TestStructTwo test2 = default(TestStructTwo);
TestStructOne test3 = default(TestStructOne);
object[] tests = new object[] { test1, test2, test3 };
if (Test(ref tests)) { //simi quazi happy dance }
1

There are 1 best solutions below

1
MakePeaceGreatAgain On BEST ANSWER

So the simple answer is no, you can´t have a method return an infinite number of references.

What should be the benefit on such a feature? Obvioulsy you want a method that can change any object no matter where it comes from nor who is using it any more. This hardly is a break on the Single-Responsibility-principle of a class, making it a God-object.

What you can do however is create the instances within an enumeration:

private bool Test(object[] differentStructures)
{
    differentStructures[0] = someOtherRessource;
    differentStructures[1] = anotherDifferentRessource
    differentStructures[2] = thirdDifferentRessource
}

And call it like:

var tests = new[] {
    default(TestStructOne),
    default(TestStructTwo),
    default(TestStructOne)
}
Test(tests);

Which will lead to the following:

tests[0] = someOtherRessource;
tests[1] = anotherDifferentRessource
tests[2] = thirdDifferentRessource