Ali
Ali

Reputation: 1678

Making a Copy of Reference itself?

Is there a way that let me make a copy of a reference itself? For example, I've a ListView control added on the form and I want to persist its Items Collection i.e.

ListViewItemCollection lvic = ListView.Items();

and when i call ListView.Items.Clear(), lvic should not be cleared.

Upvotes: 2

Views: 471

Answers (2)

Pranay Rana
Pranay Rana

Reputation: 176886

Easy way to try

  ListViewItem[] items = new ListViewItem[listView1.Items.Count];
  listView1.Items.CopyTo(items, 0);

OR

You need to create the clone of the object for that you can check this post which discuss about the cloning of the object : Cloning in C#.NET.

There are two type of cloning which is discuss in the article

1. Deep Cloning
2. Shallow Copy

Upvotes: 1

Polity
Polity

Reputation: 15130

Cloning / copying is a wide subject. It really depends on the scenario. In you case, you can simply make a copy of the collection using Linq

ListViewItem[] copiedItems = ListView.Items().OfType<ListViewItem>().ToArray();

Be carefull with cloning in this scenario. an instance of ListViewItemCollection can't be assigned to a ListView and a copy of ListView or ListViewItem still uses some native resources (in the winforms and wpf world) so copying will lead to terrible bugs when used wrongly

Upvotes: 1

Related Questions