- Home /
C# Dictionary protection level when foreach-ing
Here's the error:
error CS0122: `System.Collections.Generic.KeyValuePair<string,int>.Value' is inaccessible due to its protection level
Here's the code that triggers it:
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class HSInventoryManager : MonoBehaviour {
public Dictionary<string, int> InventoryItemsDictionary = new Dictionary<string, int>();
public void Start (){
//First, populate dictionary contents with items the player MIGHT have.
InventoryItemsDictionary.Add("Hydrogen", 0);
InventoryItemsDictionary.Add("Helium", 0);
InventoryItemsDictionary.Add("Lithium", 0);
// And so forth
bool PlayerPrefsNeedUpdate = false;
//Second, update the dictionary contents with savegame data wherever it exists, create entries otherwise
foreach( KeyValuePair<string, int> InventoryItemDictionaryEntry in InventoryItemsDictionary ) {
if( PlayerPrefs.HasKey( InventoryItemDictionaryEntry.Key )) {
InventoryItemDictionaryEntry.Value = PlayerPrefs.GetInt( InventoryItemDictionaryEntry.Key );
} else {
PlayerPrefs.SetInt(InventoryItemDictionaryEntry.Key, InventoryItemDictionaryEntry.Value);
PlayerPrefsNeedUpdate = true;
}
}
// Third, update savegame data with the fresh inventory levels, if needed.
if ( PlayerPrefsNeedUpdate ) {
PlayerPrefs.Save();
}
}
}
I have declared everything public that I can identify... so why would there be a protection level problem?
Thank you for your guidance.
Answer by Dave-Carlile · Oct 29, 2013 at 04:18 PM
The Value
property is read only.
Well, I learned something today. Thank you.
I guess this sends me back to using multiple parallel arrays or strided lists for read/write lists with text keys functionality?
Blarg.
Not at all! Just use the key to index the dictionary.
foreach( $$anonymous$$eyValuePair<string, int> InventoryItemDictionaryEntry in InventoryItemsDictionary ) {
if( PlayerPrefs.Has$$anonymous$$ey( InventoryItemDictionaryEntry.$$anonymous$$ey )) {
InventoryItemsDictionary[InventoryItemDictionaryEntry.$$anonymous$$ey] = PlayerPrefs.GetInt( InventoryItemDictionaryEntry.$$anonymous$$ey );
}
@Dave Carlile's answer was the one I deserved. @OP_toss' answer was the one I needed. :)
OP_toss++
EDIT: your solution indeed appears to have worked. In the co$$anonymous$$g inevitable apocalypse, I shall endeavor to ensure that my $$anonymous$$ions do not mangle and devour your corpse. Have a nice day.
Actually, I forgot about one thing in my answer, dictionaries will become out of sync if you attempt to alter them in a foreach loop...
Ins$$anonymous$$d you have to either copy the keys out first, and iterate over those, or maintain a list of changes to which you apply in a second loop.
See this post for more details and examples
Sorry for the confusion...
Your answer
![](https://koobas.hobune.stream/wayback/20220613120855im_/https://answers.unity.com/themes/thub/images/avi.jpg)