Readonly syntax shortcut for reading

As you know the code:

using(myDisposable) { } 

equivalently

 try { //do something with myDisposable } finally { IDisposable disposable = myDisposable as IDisposable; if(disposable != null) { disposable.Dispose(); } } 

and

 lock(_locker) { } 

equivalently

 Monitor.Enter(_locker); try { } finally { Monitor.Exit(_locker); } 

What is the equivalent of readonly field?

 readonly object _data = new object(); 
+4
source share
2 answers

A readonly object is equivalent to intialization without readonly . The main difference is that IL metadata will have the init initly bit set in the field.

Nitpick: both of your using and lock extensions are incorrect in a subtle way.

The lock version is incorrect, because its extension depends on the version of the CLR and C # compiler you are using. The C # 4.0 compiler in combination with version 4.0 uses the Enter(object, ref bool) template instead of the simple Enter(object)

The using version is subtly incorrect because it looks a little closer to this in the finally block

 if (disposable != null) { ((IDisposable)disposable).Dispose(); } 
+5
source

There is no one; that is, you cannot express the readonly field, except for the readonly keyword.

The readonly keyword is a signal to the compiler that the field can only be changed inside the class constructor.

+4
source

All Articles