Proper way in C# to combine an arbitrary number of strings into a single string

I breezed through the documentation for the string class and didn't see any good tools for combining an arbitrary number of strings into a single string. The best procedure I could come up with in my program is

string [] assetUrlPieces = { Server.MapPath("~/assets/"), 
                             "organizationName/",
                             "categoryName/",
                             (Guid.NewGuid().ToString() + "/"),
                             (Path.GetFileNameWithoutExtension(file.FileName) + "/")
                           };

string assetUrl = combinedString(assetUrlPieces);

private string combinedString ( string [] pieces )
{
    string alltogether = "";
    foreach (string thispiece in pieces) alltogether += alltogether + thispiece;
    return alltogether; 
}

but that seems like too much code and too much inefficiency (from the string addition) and awkwardness.

Jon Skeet
people
quotationmark

If you want to insert a separator between values, string.Join is your friend. If you just want to concatenate the strings, then you can use string.Concat:

string assetUrl = string.Concat(assetUrlPieces);

That's marginally simpler (and possibly more efficient, but probably insignificantly) than calling string.Join with an empty separator.

As noted in comments, if you're actually building up the array at the same point in the code that you do the concatenation, and you don't need the array for anything else, just use concatenation directly:

string assetUrl = Server.MapPath("~/assets/") +
    "organizationName/" + 
    "categoryName/" +
    Guid.NewGuid() + "/" +
    Path.GetFileNameWithoutExtension(file.FileName) + "/";

... or potentially use string.Format instead.

people

See more on this question at Stackoverflow