Beyond making the method static, here's an improved version of your method.
public static string JoinList(List<int> list)
{
StringBuilder builder = new StringBuilder("");
if (list != null)
{
foreach(int number in list)
{
builder.AppendFormat(",{0}", number);
}
if (builder.Length > 0)
{
builder.RemoveAt(0);
}
}
return builder.ToString();
}</int>
Using the
StringBuilder
is more efficient because it doesn't reallocate the string every time you add something to it.
Also, in the
foreach
loop, I could have checked to see if the string was empty for each item to avoid having the comma show up at the beginning of the string, but it's more efficient just to go ahead and create the string, and then take care of the leading comma one time after the string has been built. Just because computers have a lot of memory nowadays doesn't remove our responsibility for making the code as efficient as possible.