2 Replies - 933 Views - Last Post: 30 March 2009 - 01:20 PM Rate Topic: -----

#1 ali_selaidin   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 24-March 09

List<T> not copied...

Posted 30 March 2009 - 01:02 PM

So i have this:

List<CustomClass> list1 = new List<CustomClass>;

list1.Add(CustomClass);
list1.Add(CustomClass);

List<CustoClass> list2 = new List<CustomClass>;
list2 = list1; //the Count of list2 is equal to 2
list1.Clear(); //the Count of list2 is equal to 0

So when i clear list1, list2 is cleared as well. Why? I don't want that.

Is This A Good Question/Topic? 0
  • +

Replies To: List<T> not copied...

#2 programble   User is offline

  • (cons :dic :head)

Reputation: 50
  • View blog
  • Posts: 1,315
  • Joined: 21-February 09

Re: List<T> not copied...

Posted 30 March 2009 - 01:05 PM

Use list1.Clone()
Was This Post Helpful? 0
  • +
  • -

#3 SigurdSuhm   User is offline

  • D.I.C Head

Reputation: 18
  • View blog
  • Posts: 111
  • Joined: 05-August 08

Re: List<T> not copied...

Posted 30 March 2009 - 01:20 PM

The reason is that List<T> is a class and thus a reference type. When you assign list2 to be equal to list1 you actually point them towards the same reference instead of copying the list.

It should be easy to find some articles on reference and value types on the internet.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1