Click here to Skip to main content
15,896,430 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone, I am having a little problem with C#

I'd rather illustrate my point with a little piece of code:

C#
List<int> List1, List2;
List1 = new List<int>();

List1.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
List2 = List1;

List2.Reverse();


In the above code, after List2 is .Reversed(), the items of List1
are ALSO reversed!

I am guessing that
List2 = List1

mimics something like pointers in plain C,
ie List2 points to List1 (by reference), but
I thought that using this command I would initiate List2,
and basically "copy" List1 to List2, with List2 being an
independent entity.

Is this behaviour normal or am I missing something here?
Also, which approach do you propose to achieve what I am
looking for here?

Currently I am using
C#
List2.AddRange(List1)

instead of the above statement, which seems
to take care of the "dependency" issue
Posted

This is normal.
When you declare a list:
C#
List<int> int1;
you are declaring a variable that references a List<int> not the actual object that hold the integers - as you say, much like a pointer in plain c.
So when you declare two lists:
C#
List<int> list1 = new List<int>();
List<int> list2 = list1;
You get two references which point at the same object.
If you did it in C:
C++
int* p1 = (int*) malloc(1000);
int *p2 = p1;
*p1 = 42;
You would expect *p1 and *p2 to contain 42.

Basically, think of any variable you declare in C# as a reference - it's not true, there are value types as well - and you won't go too far wrong.
 
Share this answer
 
Comments
BlackAddler 11-Mar-12 9:52am    
Aha! Thank you, now it makes quite some sense!
In this code, those list variable are references, because the generic class System.Collections.Generic.List is class and hence a reference type.

References are analogous to pointers, but very different. They are the pointers in managed CLR world. The physical locations of the objects can be changed during run time. If you want to rely in fixed positions of object, you need to "pin" them using unsafe code. Sometime it's used for acceleration of work with the arrays, collaboration with unmanaged code and the like.

—SA
 
Share this answer
 

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