HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpModerate

Best C# idiom to convert the items on an object array to a string?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theconvertarrayidiomitemsobjectstringbest

Problem

I have something akin to

object[] values = getValues();
string renderedValues = string.Join("-", 
                          Array.ConvertAll(values,
                          new Converter(o2s)
                        ));


where o2s is

public static string o2s(object o) { return o.ToString(); }


Comments welcome!

Solution

There exists a method for that conversion already:

string renderedValues = string.Join(
  "-",
  Array.ConvertAll(values, Convert.ToString)
);


Update:

In framework 4 an overload that takes an object array was added, so it will do the conversion for you:

string renderedValues = string.Join("-", values);

Code Snippets

string renderedValues = string.Join(
  "-",
  Array.ConvertAll<object, string>(values, Convert.ToString)
);
string renderedValues = string.Join("-", values);

Context

StackExchange Code Review Q#6092, answer score: 13

Revisions (0)

No revisions yet.