[MSIL Generation] Local Array Initialisers

  • Thread starter Thread starter Cool Guy
  • Start date Start date
C

Cool Guy

After the following has been compiled, the number literal values are stored
in a special class field:

class Test {
static void Main() {
int[] arr = new int[] { 1, 2, 3 };
System.Console.WriteLine(arr[0]);
}
}

This is not true for the following, wherein the literal values are included
within the MSIL code for the method:

class Test {
static void Main() {
string[] arr = new string[] { "one", "two", "three" };
System.Console.WriteLine(arr[0]);
}
}

Does anyone know the rationale behind this?
 
Does anyone know the rationale behind this?

The strings, being reference types, must be allocated from the GC
heap. The string[] only stores references to each string object and
those references can't be known at compile time.

For ints and other simple value types the array can be quickly
initialized by storing the values sequentially in the module and
basically doing a memcpy to the array with
RuntimeHelpers.InitializeArray.


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top