This really weird thing happens when I try to set the value of an inner element in my nested list. Any ideas?

 List<List<int>> myOuterList = new List<List<int>>(); List<int> myInnerList = new List<int>(); myInnerList.Add(1); myInnerList.Add(2); myInnerList.Add(3); myOuterList.Add(myInnerList); myOuterList.Add(myInnerList); myOuterList.Add(myInnerList); myOuterList[1][2] = 5; Console.WriteLine("The value of myOuterList[1][2] should be 5, and it is: " + myOuterList[1][2]); Console.WriteLine("The value of myOuterList[2][2] should be 3, and it is: " + myOuterList[1][2]); Console.WriteLine("The value of myOuterList[1][1] should be 2, and it is: " + myOuterList[1][2]); Console.WriteLine("The value of myOuterList[1][1] should be 2, and it is: " + myOuterList[2][1]); 

My output looks like this

My 2D list looks like this.

So by attempting to set one value within the inner list myOuterList[1][2], I have somehow set [0][2], [1][2], and [2][2] — all to the same value (5).

I can't imagine why this would be, and I can't find any documentation on how to modify values inside of inner lists in nested lists.

Anyone got any ideas?

by ireadallthecomments via /r/csharp

Leave a Reply