Question Int32 on console

Chyvi

New member
Joined
Dec 7, 2022
Messages
1
Programming Experience
Beginner
Hello, such a problem that when creating an array in c # Visual studio, it displays INT32 in the console, how can I remove this
code:
int[] array = { 1, 5, 1, 6 };

Console.WriteLine(array);

Console:
System.Int32[]

Why?
 
When you pass an object to Console.WriteLine, the ToString method of that object will be called and the result displayed. The default implementation of ToString is to simply return the name of the object's type and the vast majority of types don't override that. Your object is an array of Int32 (int is an alias for System.Int32, just as string is an alias for System.String and bool is an alias for System.Boolean) so you're seeing that type name. If you want to see something different then you have to first put some thought into what that is, then you need to put some thought into the logic required to achieve it, then you need to write code to implement that logic.
 
Given that you're a beginner, you might use a loop to get each element from the array and either use Console.Write to write multiple values on the same line or else build a string from parts and then write it out with a single call to Console.WriteLine. I'll give you a glimpse of how more experienced developers would do something like this though. Assuming that you want a string containing the element values separated by commas, you could do that like this:
C#:
Console.WriteLine(string.Join(", ", array));
That may not work as is, given that int is a value type and I think that string.Join may require a reference-type list. In that case, you can do this:
C#:
Console.WriteLine(string.Join(", ", array.Cast<object>()));
 
Back
Top Bottom