I have the following code snippet:
Dictionary<int, List<string>> likeListDict = new Dictionary<int, List<string>>();
List<string> lists = new List<string>();
lists.Add("hello");
lists.Add("world");
likeListDict.Add(1, lists);
lists.Clear();
lists.Add("foobar");
likeListDict.Add(2, lists);
At the likeListDict.Add(1, lists) part, the “hello” and “world” get added in to key 1. But once I do the lists.Clear(), and add in the key 2 to likeListDict, both key 1 and 2 now have “foobar”. How do I stop this (call by reference) and make it call by value?
There is no concept of “call by reference” or “call by value”.
List<T>is a reference type, so whatever you do to a given reference will be visible anywhere in the program where that reference exists.What you want to do is create a new list instead of calling
lists.Clear();