Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Join(string, string[]) returns "System.String[]"

Tags:

arrays

c#

I need some help. I have a method that should output a txt file with the contents of a list(each item on a line). The list items are string arrays. The problem is that when I call string.Join it returns the literal string "System.String[]" instead of the actual concatenated string. I watched it in the debugger and the list and its arrays have the correct strings. Any idea how I can get the actual string so it can be written in the txt file?

Here is my code :

 public void myMethod()
    {
        List<Array> list = new List<Array>();
        for (int i = 0; i < myGrid.Rows.Count; i++)
        {
            string[] linie = new string[3];
            linie[0] = myGrid.Rows[i].Cells[1].Value.ToString();
            linie[1] = myGrid.Rows[i].Cells[3].Value.ToString();
            linie[2] = myGrid.Rows[i].Cells[2].Value.ToString();

            {
                list.Add(linie);
            }
        }
        string path = "S:\\file.txt";
        StreamWriter file = new System.IO.StreamWriter(path);
        foreach (Array x in list)
        {
            string s = string.Join(",", x);
            file.WriteLine(s);
        }
            file.Close();
  }      
like image 954
miraco Avatar asked Nov 29 '22 01:11

miraco


1 Answers

string.Join() takes a params object[].

When you pass a variable of compile-time type Array, it interprets that as a single item in the array, and it ends up passing new object[] { yourArray }.
It then calls ToString() on the single item, which returns the type name (since arrays do not override ToString().

To fix that, you need to change Array to any strongly-typed collection type (string[], object[], or IEnumerable<string>).
It will then pass the array itself to Join(), instead of assuming it's a single parameter in the paramarray.

like image 156
SLaks Avatar answered Dec 09 '22 11:12

SLaks