tags:

views:

255

answers:

3

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?

+18  A: 

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.

Femaref
+14  A: 

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

Timwi
+8  A: 

From Ecma-335. (12.4, 6)

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

Mark H
Ecma-355 is titled 'Tunnelling of QSIG over SIP'
Hans Passant
Oops, well spotted.
Mark H