Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET reflection - converting array-type property value into comma-separated string

I am inspecting .NET objects using reflection to dump them to a log.

I've hit a snag - what if a property is an array type? I do get the PropertyInfo structure for that property, and I can see that the property is an array, and I can even get the value of that array property:

if(propertyInfo.PropertyType.IsArray)
{
    var value = propertyInfo.GetValue(myObject, null);
}

but now I'm stuck. When I look in the Visual Studio debugger, it shows as int[3] - so VS knows it's an array of three integers - but how can I convert this to a comma-separated string representing these three integers now?

I tried things like

string.Join(", ", value);

and others - but I'm always struggling with the fact that value is "dynamic", e.g. it could be a int[] or a decimal[] or even something else - so I cannot statically type it.... and if I don't type it, then the string.Join() returns strange results (definitely not what I'm looking for...)

Is there any clever way to convert this "array of something" to a comma-separated string without a lot of if(...) and else { .... } clauses??

Somehow I'm in a brain-freeze here right now - any ideas to thaw this freeze up would be most welcome!

like image 982
marc_s Avatar asked Apr 02 '13 06:04

marc_s


1 Answers

Well it seems like the easiest way around this problem would be to convert it to an IEnumerable<object>. Like this:

if(propertyInfo.PropertyType.IsArray)
{
    var values = (IEnumerable)propertyInfo.GetValue(myObject, null);
    var stringValue = string.Join(", ", values.OfType<object>());
}

Although, because of array covariance in c#, if values is an array of a reference type, it should be castable to object[]. For this case, you could use this instead:

if(propertyInfo.PropertyType.IsArray)
{
    var values = (IEnumerable)propertyInfo.GetValue(myObject, null);
    var elementType = propertyInfo.PropertyType.GetElementType();
    if (elementType != null && !elementType.IsValueType)
    {
        var stringValue = string.Join(", ", (object[])values);
    }
    else
    {
        var stringValue = string.Join(", ", values.OfType<object>());
    }
}
like image 117
p.s.w.g Avatar answered Sep 27 '22 22:09

p.s.w.g