1

This rather inelegant method takes an input array of objects and outputs a string result, which is the result of ToString() for each element, space separated.

string Format(object[] args)
{
   var res = string.Empty;
   foreach (var o in args)
   {
      res += o.ToString();
      if (o != args.Last())
         res += " ";
   }
}

Surely there is a C# method hidden somewhere to do this type of operation, or if not, a more elegant way to write it using Linq? Another concern with how I have written this method is the garbage generation by building the string incrementally.

9
  • 19
    You've just recreated string.Join Commented Jul 25, 2013 at 20:41
  • What @McGarnagle said, plus it's going to fall over if o is null. Commented Jul 25, 2013 at 20:42
  • Rename your method to Join2 Commented Jul 25, 2013 at 20:43
  • 1
    What @Moo-Juice said, plus if you pass in value types they all get boxed & if there are a lot of objects you'd be better of using a StringBuilder. Plus Format is a bad name as you're not actually doing any formatting... Commented Jul 25, 2013 at 20:43
  • 1
    Looking at the implementation of String.Join, it meets all the requirements: uses stringbuilder to avoid garbage, calls ToString on each element for me, and is more elegant than even linq since it is a single static method call. This is a different accepted answer than the proposed duplicate question. Commented Jul 25, 2013 at 21:07

3 Answers 3

12
var res = String.Join(" ", args);
Sign up to request clarification or add additional context in comments.

Comments

3
var res = String.Join(" ", args.Select(x=> x != null ? x.ToString() : ""));

Will join together a string representation of each item.

5 Comments

No need for this extra null check, String.Join already handles it.
I'm calling ToString(). A null value will cause a NullReferenceException
But String.Join already uses .ToString()
String.Join<T> does .ToString() and the null test for you.
Ah, didn't know about that overload of String.Join.
1

You can use the aggregate method which I tend to prefer.

args.Where(x => x != null).Aggregate((c, n) => c.ToString() + " " + n.ToString());

1 Comment

@I4V well obv you get a null reference exception on index 2. args.Where(x => x != null).Aggregate( ... ) easily solves that problem though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.