I noticed that the C# compiler generates a ret
instruction at the end of void
methods:
.method private hidebysig static void Main(string[] args) cil managed
{
// method body
L_0030: ret
}
I've written a compiler for .NET and it works regardless if I emit a ret
statement or not (I've checked the generated IL and it's indeed not in there).
I just wonder: Is ret
on methods returning void
required for anything? It doesn't seem to do anything with the stack, so I believe it's completely unnecessary for void
methods, but I'd like to hear from someone who knows a bit more about the CLR?
ret. Returns from method, possibly returning a value. The stack transitional behavior, in sequential order, is: The return value is popped from the callee evaluation stack. The return value obtained in step 1 is pushed onto the caller evaluation stack.
Description. The ret instruction transfers control to the return address located on the stack. This address is usually placed on the stack by a call instruction. Issue the ret instruction within the called procedure to resume execution flow at the instruction following the call .
According to the C# Standard (ECMA-334), a method is defined as the following:
A method is a member that implements a computation or action that can be performed by an object or class. Methods have a (possibly empty) list of formal parameters, a return value (unless the method’s return-type is void), and are either static or non-static.
(ECMA-334; 8.7.3: Methods).
Now, the CLI standard defines the following:
Control is not permitted to simply “fall through” the end of a method. All paths shall terminate with one of these instructions: ret, throw, jmp, or (tail. followed by call, calli, or callvirt).
(ECMA-335; 12.4, 6)
This means, that in C#, a method returning void
does not need a return statement. However, as the C# compiler compiles the C# code to IL Code, which requires a path termination at the end of a method, it emits a ret
to end the method.
It is indeed required in order for the code to be verifiable. Otherwise PEVerify will output the following error message:
[IL]: Error: [(filename) : (methodname)][offset 0x00000000] fall through end of the method without returning
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With