Return nothing or return void-- What exactly does C# do at the end of a void Function() call?

c#, void, void-pointers

Solution

First off, C# is compiled into IL, so the final representation post-JIT may differ.

With a void method, the method signature in IL will be marked as `void`, and the `ret` opcode will still exist. This means, from the standpoint of IL, the "returned" value on the call stack may or may not exist, but it will never get copied and used on the call site. The `ret` opcode will only push a return value if it exists, and this is not required to exist in a `void` returning method, so in many cases, it will not return anything, even in a low level conceptual standpoint.

However, for many lower-level languages (i.e. C) "void" has a slightly different meaning. Specifically, all blocks of code must return something.

This is not the case in the CLR. A void method can truly return nothing, as the `ret` opcode is allowed to not return anything. See `OpCodes.Ret`:

Returns from the current method, pushing a return value (if present) from the callee's evaluation stack onto the caller's evaluation stack.

Problem

Consider the following C# function: ``` void DoWork() { ... } ``` The C# documentation states: When used as the return type for a method, void specifies that the method does not return a value. That seems straight-forward enough and, in most cases, that suits as a fair definition. However, for many lower-level languages (i.e. C) "void" has a slightly different meaning. Specifically, all blocks of code must return something. Therefore, `void` is a representation of the null pointer which is a representation of "nothing". In such a case, you do not need to have a `return` statement within your code because any block-statement that doesn't return a value automatically returns a null pointer. Is this what C# does or when a `void` function is called, does it execute a block of code and return without even having a pointer containing a value of void?

Original source