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?
According to the C# Standard (ECMA-334), a method is defined as the following:
(ECMA-334; 8.7.3: Methods).
Now, the CLI standard defines the following:
(ECMA-335; 12.4, 6)
This means, that in C#, a method returning
voiddoes 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 aretto end the method.