zuh4n
zuh4n

Reputation: 448

Creating a copy of a List

I need to store two variables and then check if they have not changed.

List<CatalogInfo> list_catalogs = new List<CatalogInfo>();
List<FileInfo> list_files = new List<FileInfo>(); 
List<CatalogInfo> list_catalogs_for_check_changed = new List<CatalogInfo>();
List<FileInfo> list_files_check_changed = new List<FileInfo>();

When I do:

list_catalogs_for_check_changed = list_catalogs;
list_files_check_changed = list_files;

But When I add to list_catalogs or list_files Items I see in debager that Items add to list_catalogs_for_check_changed or list_files_check_changed. Why??? I don't add Items to with variables.

  list_catalogs.Add(new CatalogInfo() { Action = "Create", Path = folderBrowserDialog1.SelectedPath });

Upvotes: 3

Views: 122

Answers (3)

germi
germi

Reputation: 4658

When you do

list_catalogs_for_check_changed = list_catalogs;

You are handing over a reference to list_catalogs. You want to copy it.

This is an article describing value types vs reference

Upvotes: 1

Ant P
Ant P

Reputation: 25221

When you do this:

list_catalogs_for_check_changed = list_catalogs;

You are not making a copy of the list, you are assigning a new reference to the same list. If you want to create a new list with the same items, do this:

    list_catalogs_for_check_changed = new List<CatalogInfo>(list_catalogs);

This assigns a new List<CatalogInfo> and passes the list from which to copy the elements, resulting in two independent lists with the same items.

Upvotes: 6

Marc Gravell
Marc Gravell

Reputation: 1062895

I don't add Items to with variables.

Indeed, you don't. You are adding items to the lists. If you do (from the question):

list_catalogs_for_check_changed = list_catalogs;
list_files_check_changed = list_files;

Then both list_catalogs_for_check_changed and list_catalogs hold a reference to the same list of CatalogInfo. Likewise, list_files and list_files_check_changed hold a reference to the same list of FileInfos. It therefore follows that if you add an item to that list, it will be visible via either variable.

The variable is not the list: the list is somewhere on the managed heap. The variable is just the reference to the list. Assigning one list variable to another copies the reference. It does not make a copy of the list.

Upvotes: 3

Related Questions