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);
}
}
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. .
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.
You could use string.Join
Console.WriteLine("Array line : "+ string.Join(",", arr));
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With