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?
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
.