0

This is really my first foray into CIL, and there must be something I don't get. I am generating a class using Reflection.Emit in C#, but getting an exception trying to use an enumerator.

getChangesIL.Emit(OpCodes.Newobj, typeof(List<PropertyChangeRecord>).GetConstructor(Type.EmptyTypes));
getChangesIL.Emit(OpCodes.Stloc_0);
getChangesIL.Emit(OpCodes.Ldarg_0);
getChangesIL.Emit(OpCodes.Ldfld, changeDict);
getChangesIL.Emit(OpCodes.Callvirt, changeDictType.GetMethod("GetEnumerator"));
getChangesIL.Emit(OpCodes.Stloc_1);
getChangesIL.Emit(OpCodes.Br_S, moveNext);
getChangesIL.MarkLabel(loopStart);
//Some loop stuff. I can comment this out and still get the exception
getChangesIL.MarkLabel(moveNext);
getChangesIL.Emit(OpCodes.Ldloc_1);
getChangesIL.Emit(OpCodes.Call, changeDictType.GetMethod("GetEnumerator").ReturnType.GetMethod("MoveNext"));
getChangesIL.Emit(OpCodes.Brtrue_S, loopStart);
getChangesIL.Emit(OpCodes.Ldloc_0);
getChangesIL.Emit(OpCodes.Ret);

The exception:

[NullReferenceException: Object reference not set to an instance of an object.]
    System.Collections.Generic.Enumerator.MoveNext() +14

I can't really see what could be null besides the dictionary I'm reading from, but that is set in the constructor

ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Newobj, changeDictType.GetConstructor(Type.EmptyTypes));
ctorIL.Emit(OpCodes.Stfld, changeDict);
ctorIL.Emit(OpCodes.Ret);

I can do the same thing in the debugger using C# without a problem, so I don't believe the class is bad, but at this point I'm at a loss as to what I'm doing wrong. What is causing this null reference exception?

svick
  • 236,525
  • 50
  • 385
  • 514

0 Answers0