Home > database >  Printing Out Different Data Types On The Same Line
Printing Out Different Data Types On The Same Line

Time:01-14

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.

CodePudding user response:

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

CodePudding user response:

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.

  •  Tags:  
  • Related