Max Li
Max Li

Reputation: 5199

Dictionary uses object as key. The key is updated outside the dictionary

Consider a simple class:

public class TestClass<Val>
{
    public Val Value{get;set;}
}

Create an instance of this class and define a dictionary where we use it as a key.

TestClass<int> TestCase = new TestClass<int>();
Dictionary<TestClass<int>, int> D = new Dictionary<TestClass<int>, int>();

Put 0 into the TestCase and add the entry to dictionary:

TestCase.Value=0
D.Add(TestCase,10)

Now the dictionary looks like this: {TestCase -> Value=0:10} Now do this:

TestCase.Value=1

Now I have in the dictionary {TestCase -> Value=1 : 10} automatically, without putting the key 'TestCase -> Value=1' into the dictionary. How can I avoid it?

Upvotes: 1

Views: 120

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

Create immutable TestCase class:

public class TestClass<Val>
{
    public TestClass(Val value)
    {
       Value = value;
    }

    public Val Value{ get; private set; }
}

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062820

Basically, don't use mutable types as keys... or if you do, make sure you never mutate the key. The first would be preferable.

An even bigger problem is that if TestClass<Val> has a custom GetHashCode() / Equals() implementation, you can completely break the dictionary, as it may no longer be able to find a value for that key, even if you give it the exact instance you started with.

Anything you use as a key should ideally be immutable. For that reason, int and string make great choices, but you can also just make your type immutable, as per @lazyberezovsky's example.

Upvotes: 4

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Actually there is one single instance of TestClass. You created it outside dictionary and then added that instance to dictionary.

If you make changes to instance it reflects inside dictionary. This is shallow copying

To avoid this problem create a deepclone of your instance and then add in dictionary. In that case changes in one will not be reflected in another.

Upvotes: 2

Related Questions