Introduction
In C#, there is an easy way to do
ToString with separator delimited for Array, List, Dictionary and
Generic IEnumerables by utilizing extension method in .NET
Background
Extension Method in .NET framework.
Using the code
Lets try a simple example without using String.Join directly.
int[] intArray = { 1, 2, 3 };
Console.WriteLine(intArray.ToString(","));
List<string> list = new List<string>{"a","b","c"};
Console.WriteLine(intArray.ToString("|"));
The extension method for achieving above.
public static string ToString<T>(this IEnumerable<T> source, string separator)
{
if (source == null)
throw new ArgumentException("Parameter source can not be null.");
if (string.IsNullOrEmpty(separator))
throw new ArgumentException("Parameter separator can not be null or empty.");
string[] array = (from s in source where s != null select s.ToString()).ToArray();
return string.Join(separator, array);
}
If the code references this ExtensionMethod class, the intelliSense in visual studio would promot you the extended ToString(string seperator) method, see the picture below,

Here are different scenarios including int array, generic collection with complex type and struct and generic dictionary with complex type as value.
static void Main(string[] args)
{
int[] intArray = { 1, 2, 3 };
Console.WriteLine(intArray.ToString(","));
ArrayList arrayList = new ArrayList() { 1, 2, 3 };
Console.WriteLine(intArray.ToString(":"));
List<Foo> foos = new List<Foo>()
{
new Foo() { Name = "foo1", Number = 1 },
new Foo() { Name = "foo2", Number = 2 },
new Foo() { Name = "foo3", Number = 3 },
};
Console.WriteLine(foos.ToString(" - "));
List<StructFoo> sfoos = new List<StructFoo>()
{
new StructFoo() { Name = "sfoo1", Number = 1 },
new StructFoo() { Name = "sfoo2", Number = 2 },
new StructFoo() { Name = "sfoo3", Number = 3 },
};
Console.WriteLine(sfoos.ToString("||"));
Dictionary<int, Foo> dictionary = new Dictionary<int, Foo>()
{
{ 1, new Foo() { Name = "foo1", Number = 1 }},
{ 2, new Foo() { Name = "foo2", Number = 2 }},
{ 3, new Foo() { Name = "foo3", Number = 3 }},
};
Console.WriteLine(dictionary.ToString(","));
Console.ReadLine();
}
class Foo
{
public string Name { get; set; }
public int Number { get; set; }
public override string ToString()
{
return "'" + Name + " " + Number + "'";
}
}
struct StructFoo
{
public string Name { get; set; }
public int Number { get; set; }
public override string ToString()
{
return "'" + Name + " " + Number + "'";
}
}
Points of Interest
.NET extension method can be applied to any customized or built in types to enhance the functionality that was not shipped originally. This simply speeds up the programming at code level. Let me know if you have better ideas or bug fix.
History
Tested with the sample code provided in the zip file.