Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly field syntactic shortcut

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();
like image 354
garik Avatar asked Jan 21 '23 00:01

garik


1 Answers

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();
}
like image 197
JaredPar Avatar answered Jan 31 '23 09:01

JaredPar