C# issue storing objects into Dictionaries

187 Views Asked by At

This seems to be simple, but I'm not sure what I'm doing wrong...

I wrote the following Class, which I further use it in a Dictionary<string, ClassName> object, as its .Value:

public class StorageList
{
    static List<int> listForStorage = new();

    public void AddToListForStorage(int number)
    {
        listForStorage.Add(number);
    }

    public List<int> GetList()
    {
        return listForStorage;
    }
}

When I run the application, I create a Dictionary<string, StorageList> and add a few elements to it:

static void Main(string[] args)
{    
    Dictionary<string, StorageList> dictionary = new();
    dictionary.Add("idOne", new StorageList());
    dictionary.Add("idTwo", new StorageList());
    dictionary["idOne"].AddToListForStorage(1);
    dictionary["idOne"].AddToListForStorage(2);
    dictionary["idTwo"].AddToListForStorage(3);
    dictionary["idTwo"].AddToListForStorage(4);
}

When printing to the console either 'idOne' or 'idTwo', I was expecting to see 1 and 2 for 'idOne' and 3 and 4 for 'idTwo. However, I see 1, 2, 3 and 4 for both 'idOne' and 'idTwo'...

foreach (var id in dictionary)
{
    foreach (var item in dictionary[id.Key].GetList())
    {
        Console.WriteLine(item);
    }
    Console.WriteLine($"Finished {id.Key}");       
}
// 1
// 2
// 3 <-- Not expected
// 4 <-- Not expected
// Finished idOne
// 1 <-- Not expected
// 2 <-- Not expected
// 3
// 4
// Finished idTwo

Objects are different, so I don't quite understand why this is happening.

Console.WriteLine(Object.ReferenceEquals(dictionary["idOne"], dictionary["idTwo"]));
// false

I'd appreciate some assistance on this. Thanks!

1

There are 1 best solutions below

5
On

You have declared listForStorage as static, so it belongs to the StorageList type rather than any specific instance of StorageList.

Consequentially, there will be only one List<int> instance used by all instances of StorageList.

That being said, you probably want to make listForStorage an instance variable (remove the static keyword):

public class StorageList
{
    List<int> listForStorage = new();
}

Now each instance of StorageList will have its own listForStorage.