1

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?

4
  • You should read the unix manual which give structures for standard types. In unix the size of structure need to be determinate. So for non standard objects the length proceeds the object when needed. String are terminated with '\n'. In Net library the structures (or classes) are not just block of contiguous memory but also contains type and size (when needed). c# has Anonymous (run time) and Non- Anonymous types (which are defined at compile time). Commented Dec 17, 2018 at 5:27
  • @JohnG of course it will not throw me an exception, please read question carefully next time Commented Dec 17, 2018 at 5:42
  • @jdweng I know how works size of types at Unix. You trying to answer on another question. Please, read question carefully next time too. Commented Dec 17, 2018 at 5:44
  • I read the question. Why do you think c# is any different than c language? The size of an object must be determinate. You said : "Array in C# is just a block of contiguous memory, just like any other language". Then saying "I know how works size of types at Unix" is a contradiction. Unix is c language and it is not just blocks of memory. Commented Dec 17, 2018 at 10:12

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.