I am currently working with lots of arrays and for debugging purposes I wrote a generic Print()
method to print different kinds of arrays
static void Main()
{
Print(new double[]{ 1, 2, 3 });
// Output: [ 1, 2, 3 ]
}
static void Print<T>(T[] array)
{
int size = array.Length;
if (size == 0)
return;
string str = "[ ";
for (int i = 0; i < size; i++)
{
str += array[i].ToString();
if (i < size - 1)
str += ", ";
}
str += " ]";
Console.WriteLine(str);
}
which works fine so far. Then I wanted to print an array of arrays, like double[][]
, and tried the following:
static void Main()
{
Print(new double[][]
{
new double[] { 1, 2 },
new double[] { 3, 4 },
new double[] { 5, 6 },
});
// Output: [ 1, 2 ]
// [ 3, 4 ]
// [ 5, 6 ]
}
static void Print<T>(T[] array)
{
if (array.Length == 0)
return;
if (array[0].GetType().IsArray)
{
foreach (var element in array)
{
Print<T>(element);
}
}
else
{
int size = array.Length;
string str = "[ ";
for (int i = 0; i < size; i++)
{
str += array[i].ToString();
if (i < size - 1)
str += ", ";
}
str += " ]";
Console.WriteLine(str);
}
}
I just wanted to check if the elements of array
again are arrays, and if so, I call the function Print again for each element
of array
. But Print(element)
doesn't work, since element
is of type T
and not T[]
and I don't know how to tell the compiler that in this case T
is an array. What do I have to do to make this work?