× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Use automatically implemented property or implement the property by ourself

Gayot Fow
Feb 05, 2015
<p>In the example you have given, the Intermediate Language (IL) would be roughly the same. </p> <p>There may be times, however, when you need to code intervention logic witout affecting the clients using it. The automatic property is great for this type of situation because it can be declared, and then later changed to add an explicit backing field. The backing field can be manipulated in the getter/setter to meet validation and verification requirements without affecting other bits of the library or assembly. The net effect is that you can make a property 'safe' without breaking changes.</p> <p>Another reason to declare a backing field occurs, for example, in WPF where a property is declared...</p> <pre><code>private string myVar; public string MyProperty { [DebuggerStepThrough] get { return myVar; } [DebuggerStepThrough] set { if (value != myVar) { myVar = value; OnPropertyChanged("MyProperty"); } } } </code></pre> <p>In this declaration, once the backing field has been assigned, the setter then calls an event handler to let external listeners know that the value of the property has changed. </p> <p>So as a general rule, you can initially declare your properties using the automatic syntax with a view towards fleshing them out with getters/setters when intervention is needed.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/8797714/Use%20automatically%20implemented%20property%20or%20implement%20the%20property%20by%20ourself/8797854">Stack Overflow</a>.</p>
comments powered by Disqus