Note that there are some explanatory texts on larger screens.

plurals
  1. POAre there any reasons to use private properties in C#?
    text
    copied!<p>I just realized that the C# <strong>property construct</strong> can also be used with a <strong>private</strong> access modifier:</p> <pre><code>private string Password { get; set; } </code></pre> <p>Although this is technically interesting, I can't imagine when I would use it since a <strong>private field</strong> involves even <strong>less ceremony</strong>:</p> <pre><code>private string _password; </code></pre> <p>and I can't imagine when I would ever need to be able to internally <strong><em>get</em> but not <em>set</em></strong> or <strong><em>set</em> but not <em>get</em></strong> a private field:</p> <pre><code>private string Password { get; } </code></pre> <p>or</p> <pre><code>private string Password { set; } </code></pre> <p>but perhaps there is a use case with <strong>nested / inherited classes</strong> or perhaps where a get/set might contain <strong>logic</strong> instead of just giving back the value of the property, although I would tend to keep properties strictly simple and let explicit methods do any logic, e.g. <code>GetEncodedPassword()</code>.</p> <p><strong>Does anyone use private properties in C# for any reason or is it just one of those technically-possible-yet-rarely-used-in-actual-code constructs?</strong></p> <h1>Addendum</h1> <p>Nice answers, reading through them I culled these uses for private properties:</p> <ul> <li>when private fields need to be lazily loaded</li> <li>when private fields need extra logic or are calculated values</li> <li>since private fields can be difficult to debug</li> <li>in order to "present a contract to yourself"</li> <li>to internally convert/simplify an exposed property as part of serialization</li> <li>wrapping global variables to be used inside your class</li> </ul>
 

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