0

I've been using the FastMember project. It contains this code:

il.Emit(OpCodes.Ldarg, 2); 
il.Emit(OpCodes.Newobj, typeof(ArgumentOutOfRangeException).GetConstructor(new[] { typeof(string) }));
il.Emit(OpCodes.Throw);

I would like to change that to just return null instead. I tried replacing it with a single line il.Emit(OpCodes.Ret);. However, I get invalid program errors using that. How do I set the return value to null using emitted code?

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
Brannon
  • 5,324
  • 4
  • 35
  • 83
  • 1
    From a simple test program I notice you also have to use `ldnull` before returning it. Have you done so? (IL is stackbased, you have to add something to the stack so you can return it) – Jeroen Vannevel May 05 '14 at 19:37
  • 2
    Almost any question in the form of "How do I do `x` in IL" can be answered with "write a simple C# program doing `x`, and use ildasm to look at the compiled IL". – Mitch May 05 '14 at 19:53

1 Answers1

4

If you just emit ret, that's like return; in C#. But you need return null;

You should use

il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Ret);
Kris Vandermotten
  • 10,111
  • 38
  • 49