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!

2
  • 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. Commented Nov 9, 2015 at 17:46
  • Possible duplicate of printing all contents of array in C# Commented Nov 9, 2015 at 17:47

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.