Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It sounds like you're after the equivalent of "const" from C++. This doesn't exist in C#. There's no way of indicating that consumers can't modify the properties of an object, but something else can (assuming the mutating members are public, of course).</p> <p>You could return a clone of the Foo as suggested, or possibly a <em>view</em> onto the Foo, as <a href="http://msdn.microsoft.com/en-us/library/ms132474.aspx" rel="noreferrer">ReadOnlyCollection</a> does for collections. Of course if you could make <code>Foo</code> an immutable type, that would make life simpler...</p> <p>Note that there's a big difference between making the <em>field</em> readonly and making the object itself immutable.</p> <p>Currently, the type itself could change things in both ways. It could do:</p> <pre><code>_Foo = new Foo(...); </code></pre> <p><em>or</em></p> <pre><code>_Foo.SomeProperty = newValue; </code></pre> <p>If it only needs to be able to do the second, the field could be readonly but you still have the problem of people fetching the property being able to mutate the object. If it only needs to do the first, and actually <code>Foo</code> is either already immutable or could be made immutable, you can just provide a property which only has the "getter" and you'll be fine.</p> <p>It's <em>very important</em> that you understand the difference between changing the value of the field (to make it refer to a different instance) and changing the contents of the object that the field refers to.</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