tags:

views:

1495

answers:

2

I am trying to figure out how to convert an arbitrary array or collection to a string via reflection and it's driving me nuts..NUTS...I'm about yay close to putting my red swingline through the computer monitor here.

So for example, given an array of Color objects, I want the default string representation of that array (you know, semicolon-delimited or whatever) using an ArrayConverter or ColorConverter or whatever the appropriate converter is. I can do this for simple object types but collections elude me.

Here's how I'm iterating the properties of an (arbitrary) object using reflection. How do I generically convert an array containing arbitrary types to a standard string representation using the appropriate converter?

Type t = widget.GetType();

System.Reflection.PropertyInfo[] props = t.GetProperties();
foreach (PropertyInfo prop in props)
{
    TypeConverter converter = TypeDescriptor.GetConverter(prop.PropertyType);
    if (converter != null)
    {
        object o = prop.GetValue(widget, null);
        att.Value = converter.ConvertToString(o);
        // This returns some BS like "System.Array [2]"
        // I need the actual data.
    }
}

EDIT: If I try this:

att.Value = o.ToString();

It returns: "System.Drawing.Color[]". Whereas I want "255,202,101;127,127,127" or whatever the default string representation is used in for example a property editor.

Thanks!

+3  A: 

There's no such thing as "standard string representation of an array". But you can always:

string stringRepresentation = 
    string.Join(",",
        Array.Convert<Foo, string>(delegate(Foo f) { return f.ToString(); }));
Anton Gogolev
I think he wants to use reflection to serialize an object's properties to a string without having to write a mapping function by hand. 95% of the time, f.ToString() will return the name of the class, which isn't very useful.
Juliet
A: 

Just calling ToString() on individual members together should work...

object[] data = GetData();
string convertedData = String.Join(",",(from item in data select item.ToString()).ToArray());
Yuliy