Sunday, July 31, 2011

Internals of Array

Arrays are most important part of your program. Almost most of the collection that you work with in .NET framework is internally maintains Array. Say for instance, if you take the List it actually internally represents T[], while Dictionary is actually an array of structure KeyValuePair internally. Hence, array forms a very important part of your program.

Few days back while browsing over internet when I found an article written one of my buddy Dhananjay Kumar here, I thought how could I forget this important section of C# language, hence in this post, I will cover some of the important things that you need to remember while you use arrays in .NET.

Arrays Vs IEnumerables

Well, when working with Collections, the first thing that will come in your mind is the IEnumerables. Well, IEnumerable is the generic implementation of any iterators. In .NET every array internally implements an IEnuerable. You may think IEnumerable as a iterable sequence, which could be applied to anything that is iterable while array on the other hand has a fixed set of values contiguously allocated. By the way, each arrays actually implements an IEnumerable internally, so eventually in .NET every array is by default an IEnumerable.

How does an array automatically implements an IEnumerable ?

Yes, if this is in your mind, then you should read this. Actually when you declare an array the C# compiler translates it into a declaration of a class System.Array.

So, if you declare

string[] xx = { "aa" };

it is same as

Array arr = {"aa"} //even though this will produce an error


Hence, even though you think that you have declared a raw array just like what you do in Say C++, you are eventually creating an instance of a class. As this class implements IEnuerable internally, you would find the GetEnumerator inside it.

Hence you can say as any array in .NET is generally an implementation of System.Array, hence you will find few methods inside an object of it like Length, Clone, GetUpperBound, GetLowerBound etc.

How about Multi-Dimensional Arrays ?

A multi-dimensional array is also the same as Single Dimentional array and actually a System.Array inside with  a Rank of anything other than 1 (based on the number of dimensionns).
Hence

int[,] dimarray = new int[2, 3];


actually represents a multi-dimentional array. Now this is actually logically separated while you access its values.


Read more: Beyond Relational
QR: internals-of-array.aspx

Posted via email from Jasper-Net