Thread: how to set values in a list of objects ?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    183

    how to set values in a list of objects ?

    Hello,

    I need to create a 2 dimensional dynamic array. I thought of using a list of objects to do so.
    The problem is:
    although there are 3 different values added to the list, it finally has 3 elements all equal to the last add ("zzz",3)!!!
    I don't understand why??!!

    Code:
    public class myData
            {
                public string str;
                public int cnt;
            }
    
    .....
    
    List<myData> list = new List<myData>();
                myData temp = new myData();
                
                temp.str= "abc";
                temp.cnt = 1;
                list.Add(temp);
    
                temp.str= "def";
                temp.cnt = 2;
                list.Add(temp);
    
                temp.str= "zzz";
                temp.cnt = 3;
                list.Add(temp);
    
                foreach (myData Info in list)
                {....}
    Can you please tell me how I can have the list values as follow ?
    ("abc",1)
    ("def",2)
    ("zzz",3)


    Thank you
    Arian

    P.S.
    I would be thankful for any suggestion to create 2 dimensional dynamic arrays, I am not sure if List of Objects is the best way?!

    P.P.S.
    I also tried Hashsets but it turned out to be only 1 element in the final set and not 3!!!
    Code:
    HashSet<myData> list = new HashSet<myData> { }
    Last edited by arian; 11-27-2015 at 10:48 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Accessing values of class objects
    By xcorpionxting in forum C++ Programming
    Replies: 2
    Last Post: 12-02-2009, 05:35 PM
  2. Objects as arguments and as return values
    By TriKri in forum C++ Programming
    Replies: 4
    Last Post: 09-27-2009, 04:18 AM
  3. Passing Objects, Constructors, Pointers, References, Values ???
    By BlackSlash12 in forum C++ Programming
    Replies: 24
    Last Post: 12-14-2007, 06:26 PM
  4. Can objects contain/return values like a function?
    By Panopticon in forum C++ Programming
    Replies: 3
    Last Post: 01-22-2003, 07:44 PM