1

How do I statically assign values to a Dictionary where the value is another class/object. Like at the following link: C#: How can Dictionary<K,V> implement ICollection<KeyValuePair<K,V>> without having Add(KeyValuePair<K,V>)?

class Settings
{
    public Dictionary<SettingKey, SettingItem> List =
        new Dictionary<SettingKey, SettingItem>()
    {
        {SettingKey.userDBName,{ theValue = "user-name", theID = 1 }},
        {SettingKey.realName,{ theValue = "real-name", theID = 2 }}   
    };
}

enum SettingKey
{
    userDBName,
    realName 
}

class SettingItem
{
    public string theValue { get; set; }
    public int theID { get; set; }
}
Community
  • 1
  • 1
Rowan Smith
  • 1,815
  • 15
  • 29

2 Answers2

5

You must initialize the objects:

public Dictionary<SettingKey, SettingItem> List =
    new Dictionary<SettingKey, SettingItem>()
{
    {SettingKey.userDBName, new SettingItem { theValue = "user-name", theID  = 1 }},
    {SettingKey.realName,   new SettingItem { theValue = "real-name", theID  = 2 }}   
};
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Use an object initializer to set the values of the SettingItem objects

public Dictionary<SettingKey, SettingItem> List =
    new Dictionary<SettingKey, SettingItem>()
{
    {SettingKey.userDBName, new SettingItem { theValue = "user-name", theID = 1 }},
    {SettingKey.realName, new SettingItem { theValue = "real-name", theID = 2 }}   
};
mlorbetske
  • 5,529
  • 2
  • 28
  • 40