Reference books says arrays are immutable.

int[] myArray = new int[3];
            myArray[0] = 1;
            myArray[1] = 2;
            myArray[2] = 3;
            int[] myarray1 = myArray;
            myarray1[1] = 3;

myarray and myarray1 both are showing result 1 3 3. but I thought myarray1=1 3 3 and myarray=1 2 3. Please share your knowledge on this.

Edited 6 Years Ago by __avd: Added [code] tags. For easy readability, always wrap programming code within posts in [code] (code blocks).

The code:

int[] myarray1 = myArray;

means that you refered myArray as myarray1, thus myarray1 is changing with myArray, every time it is changed.
So if you'd like to use 2 separate arrays than you'd rather just set the values to the same in the second array as they are in the first array with a loop.

Hope this helps.

Edited 6 Years Ago by andrewll2: Aesthetic changes

Like andrewll2 is saying, the code:
int[] myarray1 = myArray;
Makes myarray1 and myArray point to the same memory location.
So, if you change one array element it will also be changed in the other array.

Edited 6 Years Ago by ddanbe: n/a

Thanks for the Explanation. when the array refernces of both array points to a same location,then the changes reflects on both arrays. then,why don't we call arrays are mutable.

Can anyone please explain arrays are immutable with the above example.

Thanks.

A String type in C# is immutable, but in an array (by indexing) you can change the individual values at will.

Edited 6 Years Ago by ddanbe: n/a

I don't understand why arrays haven't been depreciated to make way for better use of Collections (IEnumerable). Anything an array can do a List can do better and as they're two way-transferable for interop., it doesn't make sense not to use them ;)

Maybe so, but Lists give us coder people better more functionality and make life easier. Which, I think you'll agree, is definitely a plus ;)

List<String> myMessages = new List<String>(2);
myMessages[0] = "Hello";
myMessages[1] = "World";
myMessages.Add("How are you today?");

^^^ I'm happy, compiler happy, customer happy :)

String[] myMessages = new String[2];
myMessages[0] = "Hello";
myMessages[1] = "World";
myMes...DAMMIT! >.<

=)

This question has already been answered. Start a new discussion instead.