Reputation: 6413
I'm trying to make if-else working in IL by System.Reflection and System.Reflection.Emit. This is the code which I currently have:
Label inequality = new System.Reflection.Emit.Label();
Label equality = new System.Reflection.Emit.Label();
Label end = new System.Reflection.Emit.Label();
var method = new DynamicMethod("dummy", null, Type.EmptyTypes);
var g = method.GetILGenerator();
g.Emit(OpCodes.Ldstr, "string");
g.Emit(OpCodes.Ldstr, "string");
g.Emit(OpCodes.Call, typeof(String).GetMethod("op_Equality", new Type[]{typeof(string), typeof(string)}));
g.Emit(OpCodes.Ldc_I4, 0);
g.Emit(OpCodes.Ceq);
g.Emit(OpCodes.Brtrue_S, inequality);
g.MarkLabel(inequality); //HERE it throws exception
g.Emit(OpCodes.Ldstr, "Specified strings are different.");
g.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[]{typeof(string)}));
g.Emit(OpCodes.Br_S, end);
g.Emit(OpCodes.Brfalse_S, equality);
g.MarkLabel(equality);
g.Emit(OpCodes.Ldstr, "Specified strings are same.");
g.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
g.Emit(OpCodes.Br_S, end);
g.MarkLabel(end);
g.Emit(OpCodes.Ret);
var action = (Action)method.CreateDelegate(typeof(Action));
action();
Console.Read();
Now, on line where I'm marking label it throws me this exception:
Object reference not set to an instance of an object.
But I think it's stupidity because that label is associated with new Label object. Does anybody know how can I solve this problem? Thanks.
Upvotes: 5
Views: 483
Reputation: 50114
Don't you need to define your labels as Label whatever = g.DefineLabel();
after you've defined g
?
Upvotes: 7