.NET reflection - converting an array property value to a comma delimited string

I test .NET objects using reflection to dump them to the log.

I got trapped - what if the property is an array type? I get a PropertyInfo structure for this property, and I see that this property is an array, and I can even get the property value of this array:

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

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

I tried things like

 string.Join(", ", value); 

and others, but I always struggle with the fact that value is "dynamic", for example. it could be int[] or decimal[] or even something else - so I can’t statically enter it ... and if I don’t type it, string.Join() returns strange results (definitely not what m is looking for ...)

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

Somehow, I'm now freezing from the brain - any ideas to wipe this freeze would be very welcome!

+4
source share
2 answers

Well, it seems the easiest way to solve this problem is 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 due to the covariance array in C # , if values is an array of reference type, it should be hidden before object[] . In this case, you can 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>()); } } 
+5
source

This is the simplest solution that will work for all types of collections, including arrays ( IEnumerable is the least common base we can think of):

string.Join(", ", ((IEnumerable)value).Cast<object>().Select(i => i.ToString()));

+2
source

All Articles