How to invoke Nullable.HasValue in DynamicMethod?

281 views Asked by At

I'm writing some code using DynamicMethod. Inside my DynamicMethod, I want to invoke the Nullable.HasValue (and also the Nullable.Value) properties. I've written some code to do some, but I keep getting the Operation could destabilize the runtime error.

Here's my code:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(testHasValue()(true));
        }

        delegate bool HasValueDelegate(bool? a);
        static HasValueDelegate testHasValue()
        {
            MethodInfo GetNullableHasValue = typeof(bool?).GetProperty("HasValue").GetGetMethod();

            DynamicMethod method = new DynamicMethod("Wow", typeof(bool), new Type[] { typeof(bool?) });
            ILGenerator generator = method.GetILGenerator();

            MethodInfo GetNullableValue = typeof(bool?).GetProperty("Value").GetGetMethod();            

            generator.Emit(OpCodes.Ldarg_0);
            // Callvirt results in the same error.
            generator.Emit(OpCodes.Call, GetNullableHasValue); 
            generator.Emit(OpCodes.Ret);

            return ((HasValueDelegate)(method.CreateDelegate(typeof(HasValueDelegate)))).Invoke;
        }
    }
}

I should add that according to Telerik JustDecompile, the C# code to return the HasValue property translates into IL has follows:

    static bool hasValue(bool? a)
    {
        return a.HasValue;
    }

.method private hidebysig static bool hasValue (
        valuetype [mscorlib]System.Nullable`1<bool> a
    ) cil managed 
{
    IL_0000: ldarga.s a
    IL_0002: call instance bool valuetype [mscorlib]System.Nullable`1<bool>::get_HasValue()
    IL_0007: ret
}
1

There are 1 answers

0
Vivian River On BEST ANSWER

I figured in out.

generator.Emit(OpCodes.Ldarg_0);

should be

generator.Emit(OpCodes.Ldarga_S, 0);