Search code examples
c#arraysfunctionreturn

Array returns System.Int32[]?


When I make a function to return an array with the correct results. Instead of giving me the correct results, I get as result System.Int32[]. Anyone an idea why this is?

    class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(MultiplyByLength(new int[] {2,3,1,0}));
    }

    public static int[] MultiplyByLength(int[] arr)
    {
        return arr.Select(x => x * arr.Length).ToArray();
    }
}

Solution

  • You need to format it some how. An array doesn't have a ToString() override that knows how you want to format your type (int[]) to a string, in such cases it just returns the type name (which is what you are seeing)

    foreach(var item in MultiplyByLength(new int[] {2,3,1,0})
        Console.WriteLine(item);
    

    or

    Console.WriteLine(string.Join(Environment.NewLine, MultiplyByLength(new int[] {2,3,1,0}));
    

    or

    Console.WriteLine(string.Join(",", MultiplyByLength(new int[] {2,3,1,0}));