Michael Stum
Michael Stum

Reputation: 181004

Is a ret instruction required in .NET applications?

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?

Upvotes: 19

Views: 1522

Answers (3)

Mark H
Mark H

Reputation: 13907

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

Upvotes: 8

Femaref
Femaref

Reputation: 61467

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.

Upvotes: 22

Timwi
Timwi

Reputation: 66584

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

Upvotes: 17

Related Questions