Search code examples
c#.netmemorylow-level

How C# Array works with memory?


Array in C# is just a block of contiguous memory, just like in any other language. By default taking element by index operation at T[] will cost us O(1) because of calculating index * sizeof(T). But this will work only if we know sizeof(T).

So I tried to break it:

var sampleArray = new string[10];
sampleArray[0] = "1";
sampleArray[1] = "2";

var objectArray = (object[]) sampleArray;
objectArray[2] = 42;

And predictably got runtime System.ArrayTypeMismatchException.

Ok, but today I found this example:

var arr = new[] { new object[] { new[] { 1 }, 2, "3" } };
var someValue = arr[0][1];

And this example are compiles and runs without exceptions.

Why?

How Array of objects knows the size of any element if elements are different?

How this works for strings with different length at low-level?

I don't think that Array storing 'meta' info for each element... Or maybe I was wrong?


Solution

  • String and Object are reference types, i.e. the arrays string[] and object[] contain references to the data, not the data itself.

    A reference has fixed size (32 or 64 bit depending on the processor architecture).