Is it possible to use a common dictionary as a parameter for a method that expects an IDictionary

AssemblyInstaller.Install expects System.Collections.IDictionary.

Am I right to be “allergic” to using non-shared collections like Hashtable, or should I handle it myself ?!

eg.

using System.Collections.Generic;
using System.Configuration.Install;
using System.Reflection;
using AssemblyWithInstaller;

namespace InstallerDemo
{
    class InstallerDemo
    {
        static void Main(string[] args)
        {
            var savedState = new Dictionary<object, object>();
            // i.e. as opposed to something that implements IDictionary:
            //var savedState = new System.Collections.Hashtable()
            var assembly = Assembly.GetAssembly(typeof (MyInstaller));
            var ai = new AssemblyInstaller(assembly, new[] {"/LogFile=install.log"});
            ai.Install(savedState);
            ai.Commit(savedState);
        }
    }
}

In addition, the compiler has no problem with this decalization:

var savedState = new Dictionary<string, object>();

But will anything bad happen at runtime if someone uses something other than strings as keys?


Refresh [Reflector to rescue]

var savedState = new Dictionary<string, object>();

Confirming what John says, the dictionary implements IDictionary as follows:

void IDictionary.Add(object key, object value)
{
    Dictionary<TKey, TValue>.VerifyKey(key);
    Dictionary<TKey, TValue>.VerifyValueType(value);
    this.Add((TKey) key, (TValue) value);
}

... therefore, when checking the key, it throws an exception if the type of the key does not match the type used when declaring a specific specialization of the general dictionary (and also for the value type):

private static void VerifyKey(object key)
{
    if (key == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
    }
    if (!(key is TKey))
    {
        ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
    }
}
+3
2

, Dictionary<TKey, TValue> IDictionary - , - IDictionary.Add(object, object) - ArgumentException.

, IDictionary<TKey, TValue> IDictionary - , Dictionary<TKey, TValue> IDictionary.

+2

IDictionary-Object, , . , ... , , .

, .

+4

Source: https://habr.com/ru/post/1721373/


All Articles