Search code examples
c#dictionaryextension-methods

How to make dictionary extension-methods?


I'm trying to write a Dictionary extension that works independently of the data types of Key/Value. I tried pass it by using the object data type, assuming that it will works with any type.

My code:

 public static class DictionaryExtensionsClass
    {
        public static void AddFormat(this Dictionary< ?? unknow type/*object*/, ??unknow type/*object*/> Dic, ??unknow type/*object*/ Key, string str, params object[] arglist)
        {
            Dic.Add(Key, String.Format(str, arglist));
        }
    }

Solution

  • You just make the method generic:

    public static void AddFormat<TKey>(this Dictionary<TKey, string> dictionary,
        TKey key,
        string formatString,
        params object[] argList)
    {
        dictionary.Add(key, string.Format(formatString, argList));
    }
    

    Note that it's only generic in the key type as the value would have to be string (or potentially object or an interface that string implements, I guess) given that you're going to add a string value to it.

    Unfortunately you can't really express the constraint of "only allow value types where string is a valid value" in a generic type constraint.