THIS IS NOT A DUPE OF THIS LINKED QUESTION!!!!
That question is about using the content of an object (in particular the value of a specific field of an object as a key). This question is about using they reference itself. Identical content of 2 objects would still be unique entries in this example which IS NOT WHAT THE OTHER QUESTION IS ASKING!
I agree with kevin-krumwiede in the comments that this answer is the best way to make sure what I'm doing works in all situations.
I'm using objects as keys in a Dictionary
in C#. I want to associate data with specific instances of those objects. Is this safe and supported or do I need to do more than just declare the object as the key?
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public class Program
{
public class Foo
{
}
public static void Main(string[] args)
{
Dictionary<Foo, string> dict = new Dictionary<Foo, string>();
Foo a = new Foo();
Foo b = new Foo();
Foo c = new Foo();
dict.Add(a, "bla");
dict.Add(b, "bloop");
Console.WriteLine("a in dict: " + dict.ContainsKey(a)); // true
Console.WriteLine("b in dict: " + dict.ContainsKey(b)); // true
Console.WriteLine("c in dict: " + dict.ContainsKey(c)); // false
Console.WriteLine("a's data: " + dict[a]); // bla
Console.WriteLine("b's data: " + dict[b]); // bloop
}
}
Seems to work. Any gotchas I need to be a aware of? Perf issues with using references as the key?
Note: There was this mis-labeled question that was titled "Using an object as a generic Dictionary key" but the question wasn't actually about using an Object as a key. It was about using the field of an object as a key. I fixed the title to make it clear this is a different question. I don't care what the data in the object is. I only care it's the same instance or not.