How to rewrite System.Configuration.CommaDelimitedStringCollection wrong.

We produce data in comma delimited strings. So as part of a tool we are writing, I wrote a simple loop to output a list of objects with commas between items.

public void Wrong_CommaSeperatedWriteLine(TextWriter sw, params Object[] list)
{
  if (list.Length > 0)
  {
    object last = list[list.Length - 1];

    foreach (Object obj in list)
    {
      sw.Write(obj);
      if (obj != last)
      {
        sw.Write(",");
      }
    }

    sw.WriteLine();
  }
}

Which we found today would fail when called like this:

Wrong_CommaSeperatedWriteLine(sw, "one", 2, "one");

but not this:

Wrong_CommaSeperatedWriteLine(sw, 2, 2, "one");

as the immutable strings references are the same. So while trying to think of how to avoid using a for(int i solution, I typed comma into MSDN and what do you know, CommaDelimitedStringCollection Class is there already. Doh!

So my code becomes:

public void CommaSeperatedWriteLine(TextWriter sw, params Object[] list)
{
  if (list.Length > 0)
  {
    System.Configuration.CommaDelimitedStringCollection commaStr = new System.Configuration.CommaDelimitedStringCollection();

    foreach (Object obj in list)
    {
      commaStr.Add(obj.ToString());
    }

    sw.WriteLine(commaStr.ToString());
  }
}

Gosh darn, large Libraries that solve all the simple problems (correctly) already.

There is an AddRange method but it takes a array of strings, and I have a array of objects, and I’m not sure how to auto-magic convert the arrays from one to the other. Any suggestions?

CommaDelimitedStringCollection is in the System.Configuration namespace which has to be added as a reference. There are lot of interesting classes in this namespace that I have never reviewed. Time to do some browsing…