I want to write to the debugger the content of any collection, either Dictionary. But for Dictionary, I want to identify Key and Value separatly without having to know what is the type of the key or the value.
In the following code, can I replace "KeyValuePair" with something valid in order to make the code works as expected?
[Conditional("DEBUG")]
public static void Dump<T>(this IEnumerable<T> enumerable)
{
Debug.WriteLine($"START: Enumeration of type {typeof(T).Name}");
foreach (T item in enumerable)
{
if (item is KeyValuePair kvp)
{
Debug.WriteLine($"Key: {kvp.Key,-20}, Value: {kvp.Value}");
}
else
{
Debug.Print(item?.ToString() ?? "<empty string>");
}
}
Debug.WriteLine($"END : Enumeration of type {typeof(T).Name}");
}
For the exact scenario you've asked about, the simplest approach is to write a different overload of
Dumpto handle anyIReadOnlyDictionary<K, V>, so the enumeration item type will beKeyValuePair<K, V>.But as you try to handle more cases, you'll probably want to consider recursive structures, e.g. dictionaries of lists of dictionaries, in which case your
Dumpmethod will need to become recursive and be able to accept anyobject, so it can dispatch to the right formatting code at runtime, not being at all dependent on knowing types at compile time. That's a different question though!