Search code examples
c#classdictionarykey

Dictionary with class as Key


I have measured data and I would like to store it in a 2 dimensional way. I thought I could make a Dictionary like this:

Dictionary<Key, string> dic = new Dictionary<Key, string>(); 

"Key" here is my a own class with two int variables. Now I want to store the data in this Dictionary but it doesn't work so far. If I want to read the data with the special Key, the error report says, that the Key is not available in the Dictionary.

Here is the class Key:

public partial class Key
{
    public Key(int Bahn, int Zeile) {
    myBahn = Bahn;
    myZeile = Zeile;

}
    public int getBahn()
    {
        return myBahn;
    }
    public int getZeile()
    {
        return myZeile;
    }
    private  int myBahn;
    private int myZeile;
}

for testing it I made something like this:

Getting elements in:

Key KE = new Key(1,1);
dic.Add(KE, "hans");
...

Getting elements out:

Key KE = new Key(1,1);
monitor.Text = dic[KE];

Has someone an idea?


Solution

  • You need to override methods GetHashCode and Equals in your own class to use it as a key.

    class Foo 
    { 
        public string Name { get; set;} 
        public int FooID {get; set;}
        public override int GetHashCode()             
        {  
               return FooID; 
        }
         public override bool Equals(object obj) 
        { 
                 return Equals(obj as Foo); 
        }
    
        public bool Equals(Foo obj)
         { 
              return obj != null && obj.FooID == this.FooID; 
         }
    }