1

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?

3

1 Answer 1

2

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]);
Sign up to request clarification or add additional context in comments.

3 Comments

So that means entrys.Add(entryName, new object[]{256, RegistryValueKind.DWord}); is actually not valid because a DictionaryEntry cannot hold an array as value? I thought entry.Value returns my object-array which I could acces via []-operator? Should I use an ArrayList instead or what could I do?
I have edited my answer. See the EDIT portion. Its working.
entry.Value is an object array, the dictionary is just not aware of that. That's why casting works. You might wanna use a System.Collection.Generic.HashSet<object[]> since it has a generic implementation (allows you to choose a type for the items).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.