Do I need to initobj/assign null to out arguments before ldloca and call?

119 Views Asked by At

As I see C# compiler and Reflection.Emit always emits .locals init for both value and reference type variables (even if they are later unconditionally initialized). So they can be passed as an out argument:

    .maxstack 1
    .locals init (
        [0] object x)
    L_0000: ldloca.s x
    L_0002: call void Program::MethodWithOut(object&)
    L_0007: ret 

Are there any cases where .locals is used without init so before emitting call/callvirt I need to ensure the variable is initialized?

2

There are 2 best solutions below

0
svick On BEST ANSWER

The simple answer is that init is always required to make the code verifiable. From §III.1.8.1.1 Verification algorithm of ECMA-335:

Furthermore, verifiable methods shall have the localsinit bit set […]. If this bit is not set, then a CLI might throw a Verification exception at any point where a local variable is accessed, and where the assembly containing that method has not been granted SecurityPermission.SkipVerification.

2
wertzui On

When your are passing parameters by ref you need to initialize them before passing. When you are passing parameters by out they must be initialized inside the called method.