How do I create a generic C # array content printer that accepts both objects and primitives?
I'm just trying to quickly debug a webservice by printing out the contents of an int and string array. Is there a way to do it one way?
I tried
public static string ArrayToString(object[] array)
{
StringBuilder sb = new StringBuilder();
foreach (Object item in array)
{
sb.Append(item.ToString());
sb.Append(" ");
}
return sb.ToString();
}
But it chokes when I try to send a primitive array (int []) to it due to the fact that it is not an object.
Which I find strange, since sending an int to the method below works
static void PrintObject(object obj)
{
Console.WriteLine(obj.ToString());
}
Is there a way to do this in one way, or will I just need to create and create two different methods?
Of course, whether I should be using arrays at all is dubious, but the web service already exists.
See also:
a source to share
public static string ArrayToString<T>(T[] array)
{
StringBuilder sb = new StringBuilder();
foreach (T item in array)
{
sb.Append(item.ToString());
sb.Append(" ");
}
return sb.ToString();
}
Then
int[] x = new int[] { 1, 2, 3 };
string[] y = new string[] { "a", "b", "c" };
Console.WriteLine(ArrayToString(x));
Console.WriteLine(ArrayToString(y));
a source to share
Try something like this:
static String toString<T>(IEnumerable<T> list)
{
StringBuilder sb = new StringBuilder();
foreach (T item in list)
{
sb.Append(item.ToString());
sb.Append(" ");
}
return sb.ToString();
}
The compiler will happily infer the type T
to the list type, which you loop through like this:
toString(new int[] { 1, 2, 3 });
toString(new String[] { "1", "2", "3" });
a source to share
Why did you choose an array? Your code depends on some specific properties of the array and instead just sees a list of objects. It looks like IEnumerable would be a much better choice and would allow just about any collection of objects
public static string ArrayToString(IEnumerable source)
{
StringBuilder sb = new StringBuilder();
foreach (Object item in source)
{
sb.Append(item.ToString());
sb.Append(" ");
}
return sb.ToString();
}
a source to share
There are several ways to do this.
If you have Linq you can do
int[] foo = new int[] {1,2,3,4};
ArrayToString(foo.Cast<Object>().ToArray());
and then submit it.
Or you can create a generic extension method
public static string ToString<T>(this IEnumerable<T> val)
{
StringBuilder sb = new StringBuilder();
foreach(var item in val)
{
sb.Append(item.ToString());
sb.Append(" ");
}
return sb.ToString();
}
a source to share