Let's say I have the following code:
List<Category> categories = getCategories();
List<Category> unusedCategories = categories;
foreach (var category in categories)
foreach (var imageCategory in image.Categories)
if (category.CategoryID == imageCategory.CategoryID)
unusedCategories.Remove(category);
I was getting the error that a collection was getting modified during the loop. Sure enough, as I stepped through the debugger, if remove(category) was used the "categories" list was one element shorter than before! Why does removing from "unusedCategories" affect "categories"? They should be two distinct lists, not referencing the same thing. And the .Remove() function passes by value, correct? So how does this happen?
Note: I know there are programmatic alternatives to what I'm doing above and I've already adopted one. I'm just curious why this is happening.