How data is stored
Basically an array is a blob of data. Integers are value types of 32-bit signed integers.
Identifiers in C# are either pointers to objects, or the actual values. In the case of reference types, they are real pointers, in the case of values types (e.g. int, float, etc) they are the actual data. int
is a value type, int[]
(array to integers) is a reference type.
The reason it works like this is basically "efficiency": the overhead of copying 4 bytes or 8 bytes for a value type is very small, while the overhead of copying an entire array can be quite extensive.
If you have an array containing a N integers, it's nothing more than a blob of N*4 bytes, with the variable pointing to the first element. There is no name for each element in the blob.
E.g.:
int[] foo = new int[10]; // allocates 40 bytes, naming the whole thing 'foo'
int f = foo[2]; // allocates variable 'f', copies the value of 'foo[2]' into 'f'.
Access the data
As for foreach... In C#, all collections implement an interface named IEnumerable<T>
. If you use it, the compiler will in this case notice that it's an integer array and it will loop through all elements. In other words:
foreach (int f in foo) // copy value foo[0] into f, then foo[1] into f, etc
{
// code
}
is (in the case of arrays!) the exact same thing as:
for (int i=0; i<foo.Length; ++i)
{
int f = foo[i];
// code
}
Note that I explicitly put "in the case of arrays" here. Arrays are an exceptional case for the C# compiler. If you're not working with arrays (but f.ex. with a List
, a Dictionary
or something more complex), it works a bit differently, namely by using the Enumerator
and IDisposable
. Note that this is just a compiler optimization, arrays are perfectly capable of handling IEnumerable
.
For those interested, basically it'll generate this for non-arrays and non-strings:
var e = myEnumerable.GetEnumerator();
try
{
while (e.MoveNext())
{
var f = e.Current;
// code
}
}
finally
{
IDisposable d = e as IDisposable;
if (d != null)
{
d.Dispose();
}
}
If you want a name
You probably need a Dictionary
.