How can i make params `out` in C#?

You can't have it treat the arguments as out (or ref) and make use of the params feature at the same time. It simply doesn't work. The best you can do is to create an array parameter, make the array out, declare an array variable and call the method passing the array, then inspect each element manually by index.

Foo(out object[] data) {...}
object[] result;
Foo(out result);
// look at result[0], result[1], result[2] etc

So: you cannot do what you want. Even if you could, ref / out never work unless there is an exact match between data type, so it would still have to be:

object o1, o2, o3, o4;
Foo(out o1, out o2, out o3, out o4);
// cast o1, o2, o3, o4

Which still isn't what you want.


There is no technical need for out here. This works:

void Fill(object[] p)
{
    p[0] = 1;
    p[1] = 42;
    p[2] = "Hello";
    p[3] = -1;
    p[4] = "World";
}

object[] p = new object[5];
foo.Fill(p);
i = (int)p[0];
i2 = (int)p[1];
sz = (string)p[2];
i3 = (int)p[3];
sz2 = (string)p[4];

You could return your values as Tuple:
(define your own tuple class if you're not using .NET4.0)

static Tuple<int, string> Fill()
{
    return new Tuple(42, "Hello World");
}

and then define extension methods to unpack tuples:

public static class TupleExtensions
{
    public static void Unpack<T1, T2>(
        this Tuple<T1, T2> tuple,
        out T1 item1,
        out T2 item2)
    {
        item1 = tuple.Item1;
        item2 = tuple.Item2;
    }
}

Then you can write this:

int i;
string sz;

foo.Fill().Unpack(out i, out sz);

Tags:

C#

.Net