I would like to have a mapping function that does this:
public static void Map<T>(IEnumerable<T> src, params T[] dst)
{
for (int i = 0; i < dst.Length; i++)
dst[i] = src.ElementAt(i);
}
In order to make this work dst would also have to be declared as ref, which doesn’t seem to be possible.
Here it is used in an imaginary unit test:
int a = 0, b = 0, c = 0;
int[] arr = { 1, 2, 3 };
Tools.Map(arr, a, b, c);
Assert.AreEqual(a, 1);
Assert.AreEqual(b, 2);
Assert.AreEqual(c, 3);
Is this possible at all? Does it already exist? Would it be a bad idea?
Edit: In other words, how do I give this implementation an arbitrary number of arguments:
public static void Map3<T>(IEnumerable<T> src, ref T a, ref T b, ref T c)
{
a = src.ElementAt(0);
b = src.ElementAt(1);
c = src.ElementAt(2);
}
You can’t do that. Params is a convenience by the C# compiler, which just creates an array on the spot, and populates it with the arguments.
Since an array cannot contain “ref” variables, neither can you pass “ref” to params in this way.
You are looking for something like “multiple assignment” which some languages have. If it existed, it would work something like this:
See : C#: Split string and assign result to multiple string variables
You might consider a set of extension methods:
and so on, up to as many parameters as you want to support.
It’s not an arbitrary number, but 20 should be high enough for most purposes. And hey, if it isn’t, just go higher.
Then you can use it like this:
You could even combine this with Slice to read arbitrary entries:
See slicing here: