Question

I'm currently writing a generics method to print the Key-Value pairs in a C# Dictionary; I figure its the best starting to point to get a grasp of the usefulness of this type of collection (as I did in Java with HashMaps).

There are two methods at work here:

ListWordCount(string text){// Code body}

// Returns a Dictionary<string, int> with the number of occurrences  
// Works exactly as intended (its from one of my textbooks)

And the problem method:

public static void PrintKeyValuePairs(Dictionary<IComparable, IComparable> dict)
    {
        foreach (KeyValuePair<IComparable, IComparable> item in dict)
        {
            Console.WriteLine("{0}: {1}", item.Key, item.Value);
        }

    }
// ... Some lines later
PrintKeyValuePairs( ListWordCount("Duck, duck, duck, goose") ); // Where we get the error

The current error that I'm being told is:

//"Argument 1: 
//Cannot convert from 'System.Collections.Generic.Dictionary<string, int>' to
//'System.Collections.Generic.Dictionary<System.IComparable,System.IComparable>'    "

.. Last I checked, both string and int implement 'IComparable', so I might be misunderstanding the inheritance nature, BUT I've done something very similar before that wasn't generics that worked. I would like to know how to correct for this problem so that I can prevent this sort of type conversion error in the future, or just a better way to code this general logic.

If it matters, I'm in Visual Studio 2013 on a Windows 8.1 machine.

Any help (anti-inflammatory wisdom) would be greatly appreciated.

Was it helpful?

Solution

For a generic where clause you would define it as follows:

public static void PrintKeyValuePairs<T, U>(Dictionary<T, U> dict)
        where T : IComparable
        where U : IComparable
    {
        foreach (KeyValuePair<T, U> item in dict)
        {
            Console.WriteLine("{0}: {1}", item.Key, item.Value);
        }

    }

calling it with a Dictionary<string, int> has no error:

PrintKeyValuePairs(new Dictionary<string, int> { { "duck", 4 }, { "goose", 5 } });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top