Mapping System.Int32 [] instead of array elements

I try to display the elements of an array, but I always get 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); } } 
+2
arrays c #
Aug 03 '13 at 14:34
source share
4 answers

You can use string.Join

  Console.WriteLine("Array line : "+ string.Join(",", arr)); 
+8
Aug 03 '13 at 14:36
source share

You need to iterate over the contents and print them -

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

Just printing arr will call ToString() in the array and print its type .

+6
Aug 03 '13 at 14:36
source share

Printing the array will call the ToString() method on the array, and it will print the class name, which is the default behavior. To overcome this problem, we usually redefine the ToString function of the class.

According to the discussion here, we cannot override Array.ToString () instead of List may be useful.

Simple and direct solutions have already been proposed, but I would like to make your life even easier by inserting functionality into Extension Methods (framework 3.5 or higher):

 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 to the 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 

I hope you will be very helpful.

NOTE. It should work for all data types due to the object type. I tested several of them.

+2
Aug 04 '13 at 10:25
source share

You ran into this problem because your line

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

actually prints type of arr . If you want to print element values, you must use an index number to print a value of type

 Console.WriteLine("Array line : "+arr[0]); 
0
Aug 03 '13 at 14:45
source share



All Articles