Search code examples
c#inheritancecollectionsdictionarykeyedcollection

Trying to implement Serializble DIctionary from Keyedcollection, unable to add objects


Long story short, I needed a set of objects with dictionary-like functionality that can be serialized in order to save user data. The original dictionary was a Dictionary class that held an array of Item objects and the amounts of each object 'held' by the user. After finding some recommendations on the internet I tried implmenting my own dictionary-like class from KeyedCollection, but can't seem to add objects to it. Am I adding the objects wrong or is something wrong with my collection?

The 'SerialDictionary' class:

public class SerialDictionary : KeyedCollection<Item, int>
{
    protected override int GetKeyForItem(Item target)
    {
        return target.Key;
    }
}

public class Item
{
    private int index;
    private string attribute;

    public Item(int i, string a)
    {
        index = i;
        attribute = a;
    }

    public int Key
    {
        get { return index; }
        set { index = value; }
    }

    public string Attribute
    {
        get { return attribute; }
        set { attribute = value; }
    }
}

The Main form (that is trying to add the object)

public partial class Form1 : Form
{
    SerialDictionary ItemList;
    Item orb;

    public Form1()
    {
        InitializeComponent();
        ItemList = new SerialDictionary();
        orb = new Item(0001, "It wants your lunch!");
        orb.Key = 001;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ItemList.Add(orb);
    }
}

The error I am receiving when trying to add an object:

The best overloaded method match for 'System.Collections.ObjectModel.Collection.Add(int)' has some invalid arguments

If I throw an int in there it compiles, but I'm trying to get a collection of the Item objects in there...


Solution

  • You have it backwards, it should be:

    public class SerialDictionary : KeyedCollection<int, Item>
    

    The key type comes first in the signature, then the item type.