How to make Generic code to dump to the debugger any IEnumerable and process KeyValuePair separately

37 views Asked by At

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}");
    }
1

There are 1 answers

1
Daniel Earwicker On

For the exact scenario you've asked about, the simplest approach is to write a different overload of Dump to handle any IReadOnlyDictionary<K, V>, so the enumeration item type will be KeyValuePair<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 Dump method will need to become recursive and be able to accept any object, 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!