Does this code depend on string interning to work?

Posted by Nick Gotch on Stack Overflow See other posts from Stack Overflow or by Nick Gotch
Published on 2010-01-27T15:15:21Z Indexed on 2010/05/23 5:10 UTC
Read the original article Hit count: 192

Filed under:
|

I'm creating a key for a dictionary which is a structure of two strings. When I test this method in a console app, it works, but I'm not sure if the only reason it works is because the strings are being interned and therefore have the same references.

Foo foo1 = new Foo();
Foo foo2 = new Foo();
foo1.Key1 = "abc";
foo2.Key1 = "abc";
foo1.Key2 = "def";
foo2.Key2 = "def";

Dictionary<Foo, string> bar = new Dictionary<Foo, string>();
bar.Add(foo1, "found");

if(bar.ContainsKey(foo2))
    System.Console.WriteLine("This works.");
else
    System.Console.WriteLine("Does not work");

The struct is simply:

public struct Foo
{
    public string Key1;
    public string Key2;
}

Are there any cases which would cause this to fail or am I good to rely on this as a unique key?

© Stack Overflow or respective owner

Related posts about c#

Related posts about strings