Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Int32[] displaying instead of Array elements [duplicate]

Tags:

arrays

c#

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);
    }
}
like image 479
Mitul Karnik Avatar asked Aug 03 '13 14:08

Mitul Karnik


People also ask

What does System Int32 [] mean?

Int32 is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 (which is represented by the Int32. MinValue constant) through positive 2,147,483,647 (which is represented by the Int32. MaxValue constant. .

How to copy array in c#?

copy method in C# to copy a section of one array to another. The array. copy() method allow you to add the source and destination array. With that, include the size of the section of the first array that includes in the second array.


3 Answers

You could use string.Join

 Console.WriteLine("Array line : "+ string.Join(",", arr));
like image 147
Claudio Redi Avatar answered Nov 15 '22 05:11

Claudio Redi


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.

like image 36
Rohit Vats Avatar answered Nov 15 '22 06:11

Rohit Vats


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

like image 35
NeverHopeless Avatar answered Nov 15 '22 06:11

NeverHopeless