0

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!

1
  • If you are asking for the VS debug visualizers, I don't think those are in the redistributable CLR. Commented Jul 29, 2009 at 15:58

2 Answers 2

3

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(); }));
Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.