Monday, April 25, 2011

C#/.NET interview Question - Elaborate differentiate between ArrayList and Array?

Answer:


Let’s see an example to prove the above differences.

The below is how we declare Array.

String [ ] str = new String [5]; // here you see that the length is fixed as [5]
and the data type is also defined as string.

Now, see how you can declare ArrayList.
ArrayList   str = new ArrayList (); // here you see that the length is not fixed and
is not tied up with a data type.

If you go to add data to an ArrayList you can see it takes object which is a very generic type. Due to this boxing, unboxing or casting are done. In other words data moves from stack to heap or heap to stack. If you look at Array as they are strong types boxing and unboxing are completely avoided. Therefore, Array performance is faster as compared to ArrayList.





The below diagram gives a better idea of the differences between Array and ArrayList.


Please click here to see more C#/.NET interview questions

Regards,
Visit Authors blog for more C#/.NET interviewquestion

No comments: