Click here to Skip to main content
15,902,636 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi i want to add value of a variable to a list and then change the value,
for example:


C#
static List<int> list = new List<int>();
int i=2;
list.Add(i);
int i=3;
list.Add(i);


but when i change the value of int the value of list will change.
please help me.

[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 13-Jan-15 5:24am
v2
Comments
Sergey Alexandrovich Kryukov 12-Jan-15 19:18pm    
What is that type, "List"? It could be System.Collections.Generic.List<int>...
Now, how do you "change the value of int"? What would you expect and why?
Understand simple thing: you don't add "variables", but objects. Can you see the difference?
—SA
Tomas Takac 13-Jan-15 11:31am    
Not clear. What is the problem? Your list will contain 2 and 3. Do you expect something else?

1 solution

No, it won't.
Integers are "value types" which means that when you use them you get a copy of the value instead of affecting the original.
If we make your code compile:
C#
List<int> list = new List<int>();
int i=2;
list.Add(i);
i=3;
list.Add(i);

Your list will end up with two different values on it: 2 and 3.
Try it:
C#
List<int> list = new List<int>();
int i = 2;
list.Add(i);
i = 3;
list.Add(i);
i = 4;
foreach (int item in list)
    {
    Console.WriteLine(item);
    }
list[1] += 10;
Console.WriteLine();
foreach (int item in list)
    {
    Console.WriteLine(item);
    }
You will get:
2
3

2
13
 
Share this answer
 
v2

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