As we know the code:
using(myDisposable)
{
}
is equivalent of
try
{
//do something with myDisposable
}
finally
{
IDisposable disposable = myDisposable as IDisposable;
if(disposable != null)
{
disposable.Dispose();
}
}
and
lock(_locker)
{
}
is equivalent of
Monitor.Enter(_locker);
try
{
}
finally
{
Monitor.Exit(_locker);
}
What is the equivalent of readonly
field?
readonly object _data = new object();
A readonly object is equivalent to the intialization without readonly
. The main difference is that the IL metadat will have the initonly bit set on the field.
Nitpick: Both your expansion of using
and lock
are incorrect in subtle ways.
The lock
version is incorrect because it's expansion depends on the version of the CLR and C# compiler you are using. The C# 4.0 compiler combined with the 4.0 runtime uses the Enter(object, ref bool)
pattern instead of plain Enter(object)
The using
version is subtly incorrect because it looks a bit closer to this in the finally block
if (disposable != null) {
((IDisposable)disposable).Dispose();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With