0

So right now I'm trying to print out a Console.WriteLine with elements all have different data types (string, int, and decimal).

 Console.WriteLine("Name, Credit Card Number, Balance");

        string[] Name = { "Ana", "Slova", "Nova" };
        int[] Credit = { 123242, 492913, 443112 };
        decimal[] Balance = { 12.34m, 332.33m, -3.33m };

        Console.WriteLine("{0}, {0}, {0}", Name, Credit, Balance);

Problem is they're all coming out as system string. I'm still learning C#, so any hints would be appreciated.

Nami117
  • 1
  • 3
  • Does this answer your question? [printing all contents of array in C#](https://stackoverflow.com/questions/16265247/printing-all-contents-of-array-in-c-sharp) – gunr2171 Jan 13 '22 at 22:42
  • The number in curly brackets within your string refers to the index of whatever you're wanting to display there. All three of them are set to 0 so you're displaying the first one (`Name`) 3 times. Name is 0, Credit is 1, Balance is 2, etc. You could also use [string interpolation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated) instead. – Jesse Jan 13 '22 at 22:42

2 Answers2

3

You are printing the arrays, not the content of the arrays and ToString() in arrays returns its type name.

If as I suspect you want to print a line per each "set" of data (one item from each one of the arrays) then you need to iterate these arrays per example with a for:

for(int index = 0; index < Name.Length; index++)
    Console.WriteLine("{0}, {1}, {2}", Name[index], Credit[index], Balance[index]);

Also, the format must increment its number or it will print always the first optional param passed to Console.WriteLine

Gusman
  • 14,905
  • 2
  • 34
  • 50
1
Console.WriteLine("Name, Credit Card Number, Balance");

string[] Name = { "Ana", "Slova", "Nova" };
int[] Credit = { 123242, 492913, 443112 };
decimal[] Balance = { 12.34m, 332.33m, -3.33m };

for (int i = 0; i < Name.Length; i++)
{
    Console.WriteLine("{0}, {1}, {2}", Name[i], Credit[i], Balance[i]);
}

When using ("{0}", object) the compiler calls ToString() method of the object. By using Name instead of Name[index] you are showing the default behavior of string[].ToString() which shows "System.String[]". Also the 0's in ("{0}, {0}, {0}", Name, Credit, Balance) all point to Name.

Minho17
  • 44
  • 6