0

I am trying to add values to an array and then return the whole array after 10 increments.

public int[] multi(int x)
{
    int[] array = new int[10];
    for (int i = 1; i < array.Length; i++)
    {
        array[i] = x;
        x += x;
    }
    return array;
}

When i call the method, however, it simply returns System.Int32[], instead of (in this case) 5, 10, 15, 20 etc.

int[] result = lab.multi(5);
Console.WriteLine(result);

All help appreciated!

poke
  • 369,085
  • 72
  • 557
  • 602
bovvan
  • 41
  • 1
  • 1
  • 3
  • 3
    This is by design. The default implementation of `.ToString()` defined in `Object` (from which everything derives in .NET) returns the type - in this case `System.Int32[]` (i.e., an array of `Int32`). `Console.WriteLine()` calls `ToString()` on the object. You need to loop through the array to print out the element values. – Tim Nov 09 '15 at 17:46
  • Possible duplicate of [printing all contents of array in C#](http://stackoverflow.com/questions/16265247/printing-all-contents-of-array-in-c-sharp) – poke Nov 09 '15 at 17:47

2 Answers2

3

Function Console.WriteLine calls ToString() on the object, so for reference types it simply prints the type name, which in your case is System.Int32[].

If you want to print integer array you can use function string.Join:

int[] result = lab.multi(5);
Console.WriteLine(string.Join(", ", result));
dotnetom
  • 24,551
  • 9
  • 51
  • 54
1

Console.WriteLine doesn't have an overload for int[], so it's using the object overload which calls the ToString() method. ToString on int[] prints out System.Int32[].

You need to loop through and print out each item.

foreach(var item in result)
{
    Console.WriteLine(item);
}
Dave Zych
  • 21,581
  • 7
  • 51
  • 66