private bool CanConvertKey(Type sourceType, Type targetType)
 {
     return(ConversionUtils.CanConvertElements(
                ConversionUtils.GetDictionaryKeyType(sourceType),
                ConversionUtils.GetDictionaryKeyType(targetType),
                _conversionService));
 }
        public override object Convert(object source, Type sourceType, Type targetType)
        {
            if (source == null)
            {
                return(null);
            }

            var sourceDict = source as IDictionary;
            var len        = sourceDict.Count;

            // Shortcut if possible...
            var copyRequired = !targetType.IsInstanceOfType(source);

            if (!copyRequired && len == 0)
            {
                return(source);
            }

            var targetKeyType   = ConversionUtils.GetDictionaryKeyType(targetType);
            var targetValueType = ConversionUtils.GetDictionaryValueType(targetType);
            var sourceKeyType   = ConversionUtils.GetDictionaryKeyType(sourceType);
            var sourceValueType = ConversionUtils.GetDictionaryValueType(sourceType);

            var dict = ConversionUtils.CreateCompatDictionaryFor(targetType);

            if (dict == null)
            {
                throw new InvalidOperationException("Unable to create compatable dictionary");
            }

            if (!targetType.IsGenericType)
            {
                var enumerator = sourceDict.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    dict.Add(enumerator.Key, enumerator.Value);
                }
            }
            else
            {
                var enumerator = sourceDict.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    var targetKey   = ConvertKey(enumerator.Key, sourceKeyType, targetKeyType);
                    var targetValue = ConvertValue(enumerator.Value, sourceValueType, targetValueType);
                    dict.Add(targetKey, targetValue);
                }
            }

            return(dict);
        }