Reputation: 3326
I want to do something like this:
public void PrintIDs(params int[] IDs, params string[] names)
{
// Throw error if arrays aren't same size
for (int i = 0; i = IDs.Length; i++)
Console.WriteLine($"{names[i]}: {IDs[i]}");
}
...
PrintIDs(player.ID, "Player ID", computer.ID, "Computer ID");
PrintIDs(sword1.ID, "Sword 1 ID", sword2.ID, "Sword 2 ID");
But I get an error saying: A params parameter must be the last parameter in the list
. I could just use a single params object[]
but that looses compiler and IDE support and type safety. Anyway to do this?
Upvotes: 0
Views: 139
Reputation: 3326
Using C# 7's System.ValueTuple
, you can do this:
public void PrintIDs(params (int ID, string name)[] namedIDs)
{
foreach (var namedID in namedIDs)
Console.WriteLine($"{namedID.name}: {namedID.ID});
}
Or, to be cleaner:
public void PrintIDs(params (int ID, string name)[] namedIDs)
{
foreach (var (ID, name) in namedIDs)
Console.WriteLine($"{name}: {ID});
}
And if you liked having them as two separate ways, you can use an extension method like this:
public static (T1[] array1, T2[] array2) SplitToArrays<T1,T2>(this (T1 t1, T2 t2)[] tuples)
{
var array1 = new T1[tuples.Length];
var array2 = new T2[tuples.Length];
foreach (var (i, tuple) in tuples.Index())
array1[i] = tuple.t1; array2[i] = tuple.t2;
return (array1, array2);
}
And then use it like this:
public void PrintIDs(params (int ID, string name)[] namedIDs)
{
(int[] IDs, string[] names) = namedIDs.SplitToArrays();
// OR:
var (IDs, names) = namedIDs.SplitToArrays();
for (int i = 0; i = obj.Length; i++)
Console.WriteLine($"{names[i]}: {IDs[i]}");
}
Either way, you'll call it like so:
PrintIDs((player.ID, "Player ID"), (computer.ID, "Computer ID"));
PrintIDs((sword1.ID, "Sword 1 ID"), (sword2.ID, "Sword 2 ID"));
The cool thing to is that they'll have to be the same size, which in my experience is how I wanted them anyways. If you want them different sizes, you could probably just do something like (player.ID, null)
or (player.ID, default)
and then do the proper null
or default
checking to make it so the arrays are two different sizes, using int?
instead of int
, etc.
Upvotes: 4