To understand how interlocked internals work under the hood, we're going to see what machine code is being generated when compiling the Interlocked.Increment method. If we just run the program in debug mode and look at the disassembly window, we will see the usual method call.
To see what is really going on, we have to enable all optimizations:
First, we need to build the code in the Release mode in Visual Studio.
Then, we have to go to Tools | Options | Debugging | General and uncheck the Suppress JIT optimization on module load option.
Finally, add a System.Diagnostics.Debugger.Break() method call to pause the code in debugger.
If everything is set, you will see the following code in the disassembly window:
Please notice the lock prefix in the last line of the code. This prefix is an instruction to the CPU to perform an atomic increment operation. This means that the Interlocked class is not a usual class, but a hint to the JIT compiler to generate a special code.