Erik_JI
Erik_JI

Reputation: 305

using ref or out modifiers with params modifier C#

I have the following code here and I know that this will not compile as I am trying to use the ref modifier with the params modifier:

public static int[] Findfactors(ref params int[] pro) {

    int[] hjk = { 88, 99 };
    pro = hjk;
    return pro;
}

I am just trying to make the "pro" point to the "hjk" but I can not do that. Why does't C# allow us to do that? why can't I use ref or out with params?

My best guess is the following:

The params has a property where it lets you not to pass any argument to a parameter that has the params modifier and so ,

with the example of this case, if I would not pass any argument to "pro" and then try to make pro point to "hjk", I would literally make "Nothing" point to something which would obviously not make any sense.

Upvotes: 1

Views: 342

Answers (1)

Enigmativity
Enigmativity

Reputation: 117154

Lets try to think through why this feature doesn't work.

Start with a program that does work:

void Main()
{
    int x = 1;
    Console.WriteLine(Calc(ref x));
    Console.WriteLine(x);
}

public int Calc(ref int x)
{
    x = 42;
    return x + x;
}

This outputs the following:

84
42

Now let's imagine that the ref params combination worked. I could perhaps then write this:

void Main()
{
    int x = 1;
    int y = 2;
    Console.WriteLine(Calc(ref x, ref y));
    Console.WriteLine(x);
    Console.WriteLine(y);
}

public int Calc(ref params int[] z)
{
    z = new int[] { 2, 3, };
    return z.Sum();
}

It seems reasonable that the assignment of z would result in assigning back the values of 2 & 3 to x and y, respectively.

However, there's nothing stopping me writing any of the following:

    z = new int[] { };
    z = new int[] { 2, };
    z = new int[] { 2, 3, 4, };

All of those would cause the assignment of x & y to not work.

Hence this feature cannot work.

The only way to make this work is to ensure you have two values and two values only and if you want that within a single variable then you must use tuples.

Here's how:

void Main()
{
    (int x, int y) z = (1, 2);
    Console.WriteLine(Calc(ref z));
    Console.WriteLine(z.x);
    Console.WriteLine(z.y);
}

public int Calc(ref (int x, int y) z)
{
    z = (2, 3);
    return z.x + z.y;
}

That works and outputs the following:

5
2
3

Upvotes: 1

Related Questions