For the following code I get a compile time error, *
‘int’ is not a reference type as
required by the lock statement
int i = 0;
lock(i);
But no errors for this:
int i = 0;
Monitor.Enter(i);
I understand that a value type shouldn’t be used for locking due to the complications arising due to boxing. But, then why does it work with Monitor.
The reason why is that lock is a language construct and compiler chooses to impose extra semantics on the expression. Monitor.Enter is simply a method call and the C# compiler does not special case the call in any way and hence it goes through normal overload resolution and boxing.