c# - Encapsulating how a private member variable is modified, but allowing the member to be accessible for reading -


This is a very basic OOP question. I do not want to make a copy of _objectSettings and I think that I can see a brain fart in question object in the gator function.

Example:

  Public class cool object {personal dictionary & lt; Long, bool & gt; _objectSettings; Public cool object () {//. Do stuff}} Public Zero Update Settings (Long, Boole) {// Applying New Settings Applying Some Rules} Public Dictionary & lt; Long, bool & gt; GetSettings () {// The return dictionary of settings, but users are not allowed to modify _objectSettings}}   

thanks :)

Edit: I have a Net 4.0 I am at , So the answer I choose can not show the best solution for future readers. Make either a copy or your dictionary is required in NAT 4.5, but you can easily You are not on .NET 4.5.

  public dictionary & lt; Int64, Boolean & gt; GetSettings () {// Return a snapshot of the current settings Return the new dictionary & lt; Int64, Boolean & gt; (This._objectSettings); } Public readonlyation & lt; Int64, Boolean & gt; GetSettings () {// Return only the cover wrap around the current settings New Readonization & lt; Int64, Boolean & gt; (This._objectSettings) Come back; }   

All callers will see the changes with the latter options, while the modifications made in the settings after receiving the snapshot will not be visible with the previous option.

If you want protection for unknowingly amendment in your own code base, then both options are outlined but you just return the return type IReadOnlyDictionary & lt; TKey, TValue & gt; Or you can get protection from a vulnerable IEnumerable & lt; KeyValuePair & lt; TKey, TValue & gt; & Gt; caller is just dictionary can modify and modify but this is not a big issue within your own code base.

  public IReadOnlyDictionary & lt; Int64, Boolean & gt; GetSettings () {// Just return the dictionary with the property type IReadOnlyDictionary `2 but // then the bad caller can still do the following. // ((dictionary & lt; int64, boolean & gt;) coolObject.GetSettings ()). clean (); Turn it back. _objectSettings; }   

If you reveal the object in third-party code, for example potentially malicious plug-ins, you really want to avoid this. Apart from this, you have to cancel the reflection permission because otherwise the third party code can still hold you on a private dictionary or open a cover and simply modify it.

Comments

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -