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.

Arrays are immutable so you can't add or remove items once you've created them.

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.

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.

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.

Well... because you cannot change their size.

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

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 ;)

For all we know lists may be implemented using arrays!

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! >.<

=)

Thanks everyone. Now, I am very clear.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.