Working with Dictionaries

Apr 13, 2010 at 5:00 PM

I would like to use a Dictionary on one of my data objects.  My expectation is that I would need to write a Custom Formatter to handle ToString and ToType for the KeyValuePairs in the Dictionary.  My example formatter would look something like this:

    public class DictionaryIntIntFormatter : ITypeFormatter
        public string ToString(object value)
            return string.Format("{0}|{1}", ((KeyValuePair<int, int>)value).Key, ((KeyValuePair<int, int>)value).Value);

        public object ToType(string valueString, Type expected)
            var split = valueString.Split('|');

            return new KeyValuePair<int, int>(int.Parse(split[0]), int.Parse(split[1]));

All good for the ToString, it gets called with a KeyValuePair and I turn that into a composite string.  Not so good on the ToType, it is called with a string representing a single attribute, but the type expected is the entire Dictionary.  This gives me no way to build up the Dictionary correctly.  For the sake of completeness my sample object definition is as follows:

    public class Test
        public string Id { get; set; }

        public Dictionary<int, int> Dictionary { get; set; }
I can think of a couple ways to work around this if need be, but I wanted to be sure that I wasn't missing something obvious first.  Any thoughts on how to get my expected behaviour?
Assuming there is a way to get this working, it would also be nice to be able to get the currently registered Formatter for a Type from within the Custom Formatter (in this case int) and use it for the formatting of the Key and Value.
Apr 13, 2010 at 7:14 PM

Dictionaries are not currently supported. I hadn't really planned to support them because they hold a data structure that doesn't map well to a list of SimpleDB attributes. But I can see some value in what you're doing with the list of KeyValuePairs so I may try to get this working in the near future. I'll need to do a bit of experimentation with the relevant generics reflection code first.

The simplest work-around I can suggest is to expose your dictionary to Savant as a list of KeyValuePairs and build the Dictionary from that list inside your class.

Defining Object Mappings discusses how to get the installed formatters. To get it from inside your custom formatter you would need to create and use a static reference to SavantConfig.Formatter from somewhere in your app. Or you could simply create a new PropertyFormatter instance if you just want access to the default formatters. Or you can instantiate NumberFormatter and use it directly.

Jun 17, 2010 at 5:40 PM
Dictionary formatting (with a custom formatter as described above) is now supported in Savant 0.5.1.