Making a List Builder in C#

During development, I sometimes need to create a comma-separated list of items. A custom function in your global library takes care of this mundane task with elegance and style!

The results

The code

static public string MakeList(params object[] items)
    switch (items.Length) {
	case 0:
	    // No items, just return
	    return null;
        case 1:
            // Just one
            return items[0].ToString();
        case 2:
            // Two
            return items[0].ToString() + " and " + 
            // More than two, start using commas
            string r = items[0].ToString();
            for (int i = 1; i < items.Length; i++) {
                if (i != (items.Length - 1)) {
                    // Not the last item
                    r += ", " + items[i].ToString();
                } else {
                    // Is the last item
                    r += ", and " + items[i].ToString();
            return r;

The rest

There's not a lot going on here, just standard string manipulation and logic flow. I could have used the StringBuilder class for better concatenation performance, but I figured the lists I'll be sending this function won't be very long, since they're for screen display.

One thing to pay particular attention to is the method signature. The params keyword "lets you specify a method parameter that takes an argument where the number of arguments is variable." -MSDN

I use the type object and then call .ToString() on each item to avoid having to provide strings to the method.

You could extend this method by creating an overload that offered a default value to return if the list was empty. Just make sure you put your other parameter before the params keyword. The params keyword has to be for the very last argument of the method.

Trackback URL:

Blog post currently doesn't have any comments.
Leave comment

 Security code


This web site uses Kentico CMS, the content management system for ASP.NET developers.