Problem with an array of objects using Reflection.Emit

I'm trying to emit what I thought would be a simple array of objects, which will cause the code to look like the example below

object[] parameters = new object[] { a, b, };

When I write the above code in C # using VS, I get the following IL. As expected, this works.

.locals init (
[0] object[] parameters,
[1] object[] CS$0$0000)

However, when I try to run Emit IL directly, I get only one init init array. Can someone help me tell where I was wrong here?

Here is the Emit code I'm using:

int arraySize = 2;
LocalBuilder paramValues = ilGenerator.DeclareLocal(typeof(object[]));
paramValues.SetLocalSymInfo("parameters");
ilGenerator.Emit(OpCodes.Ldc_I4_S, arraySize);
ilGenerator.Emit(OpCodes.Newarr, typeof(object));
ilGenerator.Emit(OpCodes.Stloc, paramValues);

Here is the result of IL:

.locals init (
[0] object[] objArray)

The rest of the resulting IL is identical between the two solutions, but for some reason .locals init is different.

+3
source share
3 answers

# :

object[] temp = new object[2];
temp[0] = (object)a;
temp[1] = (object)b;
parameters = temp;

CS $0 $0000, . , , , , "". , . , null . .

+3

(paramValues), . DeclareLocal , . , ? , .

0

The variable is CS$0$0000here because the compiler has not optimized the creation / use of variables. It uses this automatically generated variable for part of the new object[] { a, b, }code, and then assigns the variable to the created object object[] parameters. This behavior is mainly due to the stack-based nature of the IL. Try running the code in Release mode and see if it is optimized.

0
source

Source: https://habr.com/ru/post/1739749/


All Articles