Thread: List.Add is changing existing members?

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    3

    List.Add is changing existing members?

    I'm using the .Add() method of the .NET List to add new members. Trouble is, this seems to be changing all existing members to be the same as the added one.

    This a problem anyone has come across before?

    Console screenshot

    And here's the offending code, with my debug output code either side:

    Code:
                    System.Console.WriteLine("\nWhat I'm adding: ");
                    System.Console.WriteLine(bufferCentroid.ToString());
    
                    centroids.Add(bufferCentroid);
    
                    System.Console.WriteLine("List contains: ");
                    for (int k = 0; k < centroids.Count(); k++)
                    {
                        System.Console.WriteLine(centroids[k].ToString());
                    }

  2. #2
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    431
    centroids.Add(bufferCentroid);
    Simply adds a reference to the list, and since you're re-using the same reference, all items in the list point to the same object. What you want to do is actually create new objects (using new).
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    3
    Aha!

    Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Debugger : watching data members or arrays
    By rogster001 in forum C++ Programming
    Replies: 2
    Last Post: 11-10-2009, 07:02 AM
  2. Changing windows without changing?
    By Lionmane in forum Windows Programming
    Replies: 7
    Last Post: 10-19-2005, 11:41 AM
  3. How many forums members to change a lightbulb.
    By adrianxw in forum A Brief History of Cprogramming.com
    Replies: 21
    Last Post: 01-01-2004, 08:31 PM
  4. Accidentally changing class members??
    By JaWiB in forum C++ Programming
    Replies: 3
    Last Post: 11-01-2003, 01:42 AM
  5. Changing a Structures Members array size
    By Xei in forum C++ Programming
    Replies: 1
    Last Post: 11-07-2002, 07:45 PM