<p>In Microsoft IL, to call a method on a value type you need an indirect reference. Lets say we have an ILGenerator named "il" and that currently we have a Nullable on top of the stack, if we want to check whether it has a value then we could emit the following:</p>

<pre><code>var local = il.DeclareLocal(typeof(Nullable&lt;int&gt;));
il.Emit(OpCodes.Stloc, local);
il.Emit(OpCodes.Ldloca, local);
var method = typeof(Nullable&lt;int&gt;).GetMethod("get_HasValue");
il.EmitCall(OpCodes.Call, method, null);
</code></pre>

<p>However it would be nice to skip saving it as a local variable, and simply call the method on the address of the variable already on the stack, something like:</p>

<pre><code>il.Emit(/* not sure */);
var method = typeof(Nullable&lt;int&gt;).GetMethod("get_HasValue");
il.EmitCall(OpCodes.Call, method, null);
</code></pre>

<p>The ldind family of instructions looks promising (particularly ldind_ref) but I can't find sufficient documentation to know whether this would cause boxing of the value, which I suspect it might.</p>

<p>I've had a look at the C# compiler output, but it uses local variables to achieve this, which makes me believe the first way may be the only way. Anyone have any better ideas?</p>

<p>**** Edit: Additional Notes ****</p>

<p>Attempting to call the method directly, as in the following program with the lines commented out, doesn't work (the error will be "Operation could destabilise the runtime"). Uncomment the lines and you'll see that it does work as expected, returning "True".</p>

<pre><code>var m = new DynamicMethod("M", typeof(bool), Type.EmptyTypes);
var il = m.GetILGenerator();
var ctor = typeof(Nullable&lt;int&gt;).GetConstructor(new[] { typeof(int) });
il.Emit(OpCodes.Ldc_I4_6);
il.Emit(OpCodes.Newobj, ctor);
//var local = il.DeclareLocal(typeof(Nullable&lt;int&gt;));
//il.Emit(OpCodes.Stloc, local);
//il.Emit(OpCodes.Ldloca, local);
var getValue = typeof(Nullable&lt;int&gt;).GetMethod("get_HasValue");
il.Emit(OpCodes.Call, getValue);
il.Emit(OpCodes.Ret);
Console.WriteLine(m.Invoke(null, null));
</code></pre>

<p>So you can't simply call the method with the value on the stack because it's a value type (though you could if it was a reference type).</p>

<p>What I'd like to achieve (or to know whether it is possible) is to replace the three lines that are shown commented out, but keep the program working, without using a temporary local.</p>

[{'answer_id': 76320, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': 3, 'selected': True, 'text': '<p>If the variable is already on the stack, you can go ahead and just emit the method call.  </p>\n\n<p>It seems that the constructor doesn\'t push the variable on the stack in a typed form.  After digging into the IL a bit, it appears there are two ways of using the variable after constructing it.  </p>\n\n<p>You can load the variable that will store the reference onto the evaluation stack before calling the constructor, and then load that variable again after calling the constructor like so:</p>\n\n<pre><code>DynamicMethod method = new DynamicMethod("M", typeof(bool), Type.EmptyTypes);\nILGenerator il = method.GetILGenerator();\nType nullable = typeof(Nullable&lt;int&gt;);\nConstructorInfo ctor = nullable.GetConstructor(new Type[] { typeof(int) });\nMethodInfo getValue = nullable.GetProperty("HasValue").GetGetMethod();\nLocalBuilder value = il.DeclareLocal(nullable);         \n\n// load the variable to assign the value from the ctor to\nil.Emit(OpCodes.Ldloca_S, value);\n// load constructor args\nil.Emit(OpCodes.Ldc_I4_6);\nil.Emit(OpCodes.Call, ctor);\nil.Emit(OpCodes.Ldloca_S, value);\n\nil.Emit(OpCodes.Call, getValue);\nil.Emit(OpCodes.Ret);\nConsole.WriteLine(method.Invoke(null, null));\n</code></pre>\n\n<p>The other option is doing it the way you have shown.  The only reason for this that I can see is that the ctor methods return void, so they don\'t put their value on the stack like other methods.  It does seem strange that you can call Setloc if the new object isn\'t on the stack.</p>\n'}, {'answer_id': 90650, 'author': 'Nick Johnson', 'author_id': 12030, 'author_profile': 'https://Stackoverflow.com/users/12030', 'pm_score': 1, 'selected': False, 'text': "<p>After looking at the options some more and further consideration, I think you're right in assuming it can't be done. If you examine the stack behaviour of MSIL instructions, you can see that no op leaves its operand(s) on the stack. Since this would be a requirement for a 'get address of stack entry' op, I'm fairly confident one doesn't exist.</p>\n\n<p>That leaves you with either dup+box or stloc+ldloca. As you've pointed out, the latter is likely more efficient.</p>\n\n<p>@greg: Many instructions leave their <em>result</em> on the stack, but no instructions leave any of their <em>operands</em> on the stack, which would be required for a 'get stack element address' instruction.</p>\n"}, {'answer_id': 10883566, 'author': 'Mark', 'author_id': 64084, 'author_profile': 'https://Stackoverflow.com/users/64084', 'pm_score': 0, 'selected': False, 'text': "<p>Just wrote a class that does what the OP is asking... here's the IL code that C# compiler produces:</p>\n\n<pre><code>  IL_0008:  ldarg.0\n  IL_0009:  ldarg.1\n  IL_000a:  newobj     instance void valuetype [mscorlib]System.Nullable`1&lt;int32&gt;::.ctor(!0)\n  IL_000f:  stfld      valuetype [mscorlib]System.Nullable`1&lt;int32&gt; ConsoleApplication3.Temptress::_X\n  IL_0014:  nop\n  IL_0015:  ret\n</code></pre>\n"}, {'answer_id': 36076570, 'author': 'Mayoor', 'author_id': 4167620, 'author_profile': 'https://Stackoverflow.com/users/4167620', 'pm_score': 2, 'selected': False, 'text': '<p>I figured it out! Luckily I was reading about the <code>unbox</code> opcode and noticed that it pushes the <strong>address</strong> of the value. <code>unbox.any</code> pushes the actual value. So, in order to call a method on a value type without having to store it in a local variable and then load its address, you can simply <code>box</code> followed by <code>unbox</code>. Using your last example:</p>\n\n<pre><code>var m = new DynamicMethod("M", typeof(bool), Type.EmptyTypes);\nvar il = m.GetILGenerator();\nvar ctor = typeof(Nullable&lt;int&gt;).GetConstructor(new[] { typeof(int) });\nil.Emit(OpCodes.Ldc_I4_6);\nil.Emit(OpCodes.Newobj, ctor);\nil.Emit(OpCodes.Box, typeof(Nullable&lt;int&gt;)); // box followed by unbox\nil.Emit(OpCodes.Unbox, typeof(Nullable&lt;int&gt;));\nvar getValue = typeof(Nullable&lt;int&gt;).GetMethod("get_HasValue");\nil.Emit(OpCodes.Call, getValue);\nil.Emit(OpCodes.Ret);\nConsole.WriteLine(m.Invoke(null, null));\n</code></pre>\n\n<p>The downside to this is that boxing causes memory allocation for the boxed object, so it is a bit slower than using local variables (which would already be allocated). But, it saves you from having to determine, declare, and reference all of the local variables you need.</p>\n'}]
['https://Stackoverflow.com/questions/76274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13552/']