5

I am trying to display array elements but always getting this output System.Int32[] instead of integer elements.

using System.IO;
using System;

class Test
{
    public static void Main()
    {
        int[] arr=new int [26];
        for(int i = 0; i < 26; i++)
        arr[i] = i;

        Console.WriteLine("Array line : "+arr);
    }
}
jeremy
  • 9,455
  • 4
  • 36
  • 57
Mitul Karnik
  • 135
  • 1
  • 3
  • 11
  • possible duplicate of [c# - printing contents of array](http://stackoverflow.com/questions/3700448/c-sharp-printing-contents-of-array) and http://stackoverflow.com/questions/145856/how-to-join-int-to-a-character-separated-string-in-net – user7116 Aug 03 '13 at 14:46
  • If you still have any ambiguity have a look at my suggestion. – NeverHopeless Aug 04 '13 at 17:35

4 Answers4

13

You could use string.Join

 Console.WriteLine("Array line : "+ string.Join(",", arr));
Claudio Redi
  • 63,880
  • 13
  • 118
  • 146
6

You need to loop over the content and print them -

Console.WriteLine("Array line: ");
for(int i=0;i<26;i++)
{
     arr[i]=i;
     Console.WriteLine(" " + arr[i]);
}

Simply printing arr will call ToString() on array and print its type.

Rohit Vats
  • 74,365
  • 12
  • 144
  • 173
2

Printing an array will call the ToString() method of an array and it will print the name of the class which is a default behaviour. To overcome this issue we normally overrides ToString function of the class.

As per the discussion here we can not override Array.ToString() instead List can be helpful.

Simple and direct solutions have already been suggested but I would like to make your life even more easier by embedding the functionality in Extension Methods (framework 3.5 or above) :

public static class MyExtension
{
    public static string ArrayToString(this Array arr)
    {
        List<object> lst = new List<object>();
        object[] obj = new object[arr.Length];
        Array.Copy(arr, obj, arr.Length);

        lst.AddRange(obj);
        return string.Join(",", lst.ToArray());
    }
}

Add the above code in your namespace and use it like this: (sample code)

float[] arr = new float[26];
for (int i = 0; i < 26; i++)
    arr[i] = Convert.ToSingle(i + 0.5);

string str = arr.ArrayToString();
Debug.Print(str);  // See output window

Hope you will find it very helpful.

NOTE: It should work for all the data types because of type object. I have tested on few of them

NeverHopeless
  • 10,503
  • 4
  • 33
  • 53
1

You are facing this problem because your line

Console.WriteLine("Array line : "+arr);

is actually printing the type of arr. If you want to print element values you should use the index number to print the value like

Console.WriteLine("Array line : "+arr[0]);
Ehsan
  • 28,801
  • 6
  • 51
  • 61