Igor Ševo
Igor Ševo

Reputation: 5515

Converting value type array to reference type array

I need to write an exception class that takes a message and an info object of any type (usually anonymous object).

I have the following code:

public SpecialException(string message, object info) : this(message)
{
    StringBuilder sb = new StringBuilder();
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(info.GetType()))
    {
        object value = property.GetValue(info);
        string valueStr = value.GetType().IsArray ? (value as IEnumerable<object>).Select(x => x.ToString()).Aggregate((x, y) => $"{x}, {y}") : value.ToString();
        sb.AppendLine($"{property.Name} = {valueStr}");
    }
    Info = sb.ToString();
}

The problem is, this code does not work when one of the anonymous object's properties is an array of value-typed items since they do not inherit object and this type of covariance cannot work with them.

What I tried, but found either not to work or inelegant:

I assume there is an elegant way (probably using reflection) to achieve this, perhaps by somehow iterating through the array. Can anyone suggest a solution?

Upvotes: 0

Views: 98

Answers (1)

user4003407
user4003407

Reputation: 22102

Variance does not work for value types. So that, value type array can not be casted to IEnumerable<object>, but it still can be casted to non-generic IEnumerable interface. After that you can call Cast<object>() extension method to get IEnumerable<object> instance.

((IEnumerable)value).Cast<object>()

Upvotes: 1

Related Questions