Getting an error when I try to use DynamicMethod to create a method that always returns true

186 views Asked by At

Today, I started learning about the DynamicMethod class. For learning purposes, I set about to use DynamicMethod to create a function that takes no argument and always returns the boolean value true.

I created a function to do this in C# and then examined the resulting IL code with Telerik JustDecompile.

.method public hidebysig instance bool ReturnTrue1 () cil managed 
{
    .locals init (
        [0] bool CS$1$0000
    )

    IL_0000: nop
    IL_0001: ldc.i4.1
    IL_0002: stloc.0
    IL_0003: br.s IL_0005

    IL_0005: ldloc.0
    IL_0006: ret
}

It looks simple enough. According to the documentation, it looks like these instructions simply place an integer 1 on the stack to be returned.

Following along with some of the examples I've looked at, I wrote the following Console Application.

using System;
using System.Reflection.Emit;

namespace EntityFrameworkDynamicMethod
{
    class Program
    {
        static void Main(string[] args)
        {            
            ReturnTrue ReturnTrueDelegate = GetReturnTrueDelegate();
            ReturnTrueDelegate();            
        }        

        delegate bool ReturnTrue();

        static ReturnTrue GetReturnTrueDelegate()
        {            
            DynamicMethod method = new DynamicMethod("ReturnTrue", typeof(bool), new Type[] {});
            ILGenerator generator = method.GetILGenerator();
            Label IL_0005 = generator.DefineLabel();
            generator.Emit(OpCodes.Nop);
            generator.Emit(OpCodes.Ldc_I4_1);
            generator.Emit(OpCodes.Stloc_0);            
            generator.Emit(OpCodes.Ldloc_0, IL_0005);            
            generator.MarkLabel(IL_0005);
            generator.Emit(OpCodes.Ret);

            return (ReturnTrue)method.CreateDelegate(typeof(ReturnTrue));
        }
    }
}

However, when I run this code, the following exception is raised on ReturnTrueDelegate();

System.Security.VerificationException: Operation could destabilize the runtime.
at ReturnTrue()

What does this exception mean and what do I do to fix this?

1

There are 1 answers

1
SLaks On BEST ANSWER
generator.Emit(OpCodes.Ldloc_0, IL_0005);

This is incorrect; the ldloc.0 instruction has no arguments (did you mean br.s?).
You also cannot use local 0 without declaring it.

However, you don't need any of that; all you need to do is load 1 (ldc.i4.1) and return it (ret).
If you decompile release-mode code, you should see that.