Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
2.18/5 (5 votes)
See more:
I have a class as below:
C#
class EUInput
{
    public EUInput()
    {
        RtID = 0;
    }

    public int RtID { get; set; }
}


I want to store this class with different RtID values in a list. I tried as below:
C#
static void Main(string[] args)
{
    EUInput clsEUInput = new EUInput();

    List<euinput> list = new List<euinput>();

    for (int i = 0; i < 5; i++)
    {
        clsEUInput.RtID = i;
        list.Add(clsEUInput);
    }

    foreach (EUInput obj in list)
    {
        Console.WriteLine(obj.RtID.ToString());
    }


    Console.ReadLine();
}


I am getting an output as

4
4
4
4
4

But I need an outupt as

0
1
2
3
4
Posted
Updated 16-Jul-15 3:16am
v2
Comments
[no name] 16-Jul-15 9:13am    
That is because you are storing the same object in the list.
Sergey Alexandrovich Kryukov 16-Jul-15 10:16am    
Of classes, or perhaps instances of some class(es)? :-)
—SA
Matt T Heffron 16-Jul-15 12:23pm    
+4 (Not a "bad" question, just inexperience.)

1 solution

This is the error like Wes Aday already pointed:

//EUInput clsEUInput = new EUInput();


You have to create the new objects in the for-loop for each new value:

C#
        static void Main(string[] args)
        {
            //EUInput clsEUInput = new EUInput();
            EUInput clsEUInput;
 
            List<euinput> list = new List<euinput>();
           
            for (int i = 0; i < 5; i++)
            {
                // you need to create new object every time
                clsEUInput = new EUInput();
                clsEUInput.RtID = i;
                list.Add(clsEUInput);                
            }
 
            foreach (EUInput obj in list)
            {
                Console.WriteLine(obj.RtID.ToString());                
            }
 
          
            Console.ReadLine();
        }
</euinput></euinput>
 
Share this answer
 
v3
Comments
guruece24 16-Jul-15 9:25am    
I told that to my boss, he is not accepting it and asking any other solution?
[no name] 16-Jul-15 9:28am    
Sure there is. Get a new boss.
phil.o 16-Jul-15 9:28am    
What is he not accepting? The fact that a new object has to be created at each iteration? I'm sorry, no pun intended, but if it is so, he's a moron.
Sergey Alexandrovich Kryukov 16-Jul-15 10:19am    
Than think who are talking with. If you don't make any decisions, why you are wasting out time here? Let your "boss" asking questions.
—SA
Sergey Alexandrovich Kryukov 16-Jul-15 10:17am    
5ed.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900