SimonH
SimonH

Reputation: 1425

How to access an object array as Hashvalue in C#

Why does the following throws the compile error [] cannot be applied to object. (rough translation from german)?

Hashtable entrys = new Hashtable();
string keyPath = "HKEY_CURRENT_USER\\Software\\Test";
string entryName = "testName";

entrys.Add(entryName, new object[]{256, RegistryValueKind.DWord}); // seems to work

foreach(DictionaryEntry entry in entrys)
{
    Registry.SetValue(keyPath,
                      (string)entry.Key,
                      entry.Value[0],   // error here
                      entry.Value[1]);  // and here
}

I expected entry.Value to be an array of objects but apparently the compiler thinks it's just an object. What is wrong here?

Upvotes: 1

Views: 320

Answers (1)

Gagan Jaura
Gagan Jaura

Reputation: 719

The error is coming because DictionaryEntry does not have an array as a property for Value. Below is the structure of DictionaryEntry. You must use entry.Value instead of entry.Value[0]

    // Summary:
    // Defines a dictionary key/value pair that can be set or retrieved.
    [Serializable]
    [ComVisible(true)]
    public struct DictionaryEntry
    {            
        public DictionaryEntry(object key, object value);

        // Summary:
        //     Gets or sets the key in the key/value pair.
        //
        // Returns:
        //     The key in the key/value pair.
        public object Key { get; set; }
        //
        // Summary:
        //     Gets or sets the value in the key/value pair.
        //
        // Returns:
        //     The value in the key/value pair.
        public object Value { get; set; }
    }

EDIT

To make it work you have to cast it. Use following code

Registry.SetValue(keyPath,
                  (string)entry.Key,
                  ((object[])(entry.Value))[0]);

Upvotes: 2

Related Questions