C# Switch type for multiple Dictionary types

Viewed 74

I want to add Switch case based on type of input parameter. E.g. My input parameter can be of type double, Dictionary<int, string>, Dictionary<decimal, bool>

For that I have added below switch case which calls correctly for both Dictionary types mentioned above but from there i have to call another function which will log that Dictionary. For that function i have taken input as Dictionary<object, object> so that it can accept both types of dictionary but it is unable to cast above dictionary types to Dictionary<object, object>

Below is my complete code

static void Main(string[] args) {
    Dictionary < int, string > dict = new Dictionary < int, string > () {
        {
            1,
            "One"
        }, {
            2,
            "Two"
        }
    };
    Dictionary < decimal, bool > dict2 = new Dictionary < decimal, bool > () {
        {
            1,
            true
        }, {
            2,
            false
        }
    };
    Double doubleObj = 100.2;

    HandleLogging(doubleObj);
    HandleLogging(dict);
    HandleLogging(dict2);
}

private static void HandleLogging(Object obj) {
    switch (obj) {
    case double _:
        Console.WriteLine($"Dobule data type ..");
        break;

    case Dictionary < int, string > _:
    case Dictionary < decimal, bool > _:
        // case object dictType2 when dictType2 == typeof(Dictionary<decimal, bool>):

        //case Dictionary<object, object> d:
        Console.WriteLine($"Dictionary data type..");
        HandleDictionary((Dictionary < object, object > ) obj);
        break;
    default:
        Console.WriteLine("unknown type");
        break;
    }
}

private static void HandleDictionary(Dictionary < object, object > existingDictionary) {
    Console.WriteLine(string.Format("Dictionary object : {0}", JsonConvert.SerializeObject(existingDictionary)));
}
1 Answers

From pure "how do I do it" point of view (without discussing why and is it a good practice in general case) - Dictionary<TKey, TValue> implements IDictionary (which is non-generic version of dictionary) so you can match against it:

case IDictionary _:
   Console.WriteLine($"Dictionary data type..");
   Console.WriteLine("Dictionary object : {0}", JsonConvert.SerializeObject(obj));
   break;
Related