Reputation: 5515
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:
Dictionary<string, object>
- Cannot override the Add
methodIDictionary<string, object>
interface - Do not want to implement all of the interface's methods for a simple exceptionExpandoObject
and dynamic
keyword - Will run into the same problems as the code abovedynamic
and Newtonsoft JSON - Do not want a dependancy on a third-party library (or the Web DLL)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
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