Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Just thought I would share my findings on this topic.</p> <p>Coding a property like the following, is a .net 3.0 shortcut call “<strong>auto-implemented property</strong>”. </p> <pre><code>public int MyProperty { get; set; } </code></pre> <p>This saves you some typing. The long way to declare a property is like this:</p> <pre><code>private int myProperty; public int MyProperty { get { return myProperty; } set { myProperty = value; } } </code></pre> <p>When you use the “auto-implemented property” the compiler generates the code to wire up the get and set to some “k_BackingField”. Below is the disassembled code using Reflector. </p> <pre><code>public int MyProperty { [CompilerGenerated] get { return this.&lt;MyProperty&gt;k__BackingField; } [CompilerGenerated] set { this.&lt;MyProperty&gt;k__BackingField = value; } } </code></pre> <p><em>disassembled C# code from IL</em></p> <p>Also wires up a method for the setter and getter.</p> <pre><code>[CompilerGenerated] public void set_MyProperty(int value) { this.&lt;MyProperty&gt;k__BackingField = value; } [CompilerGenerated] public int get_MyProperty() { return this.&lt;MyProperty&gt;k__BackingField; } </code></pre> <p><em>disassembled C# code from IL</em></p> <p>When you declare a read only auto-implemented property, by setting the setter to private: </p> <pre><code> public int MyProperty { get; private set; } </code></pre> <p>All the compiler does flag the "<strong>set</strong>" as private. The setter and getter method say the same.</p> <pre><code>public int MyProperty { [CompilerGenerated] get { return this.&lt;MyProperty&gt;k__BackingField; } private [CompilerGenerated] set { this.&lt;MyProperty&gt;k__BackingField = value; } } </code></pre> <p><em>disassembled C# code from IL</em></p> <p>So I am not sure why the framework require both the get; and set; on an auto-implemented property. They could have just not written the set and setter method if it was not supplied. But there may be some compiler level issue that makes this difficult, I don't know.</p> <p>If you look at the long way of declaring a read only property:</p> <pre><code>public int myProperty = 0; public int MyProperty { get { return myProperty; } } </code></pre> <p>And then look at the disassembled code. The setter is not there at all.</p> <pre><code>public int Test2 { get { return this._test; } } public int get_Test2() { return this._test; } </code></pre> <p><em>disassembled C# code from IL</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload