c# - How can I make a read only version of a class? -
i have class various public properties allow users edit through property grid. persistence class serialized/deserialized to/from xml file through datacontractserializer.
sometimes want user able save (serialize) changes they've made instance of class. yet @ other times don't want allow user save changes, , should instead see properties in property grid read only. don't want allow users make changes they'll never able save later. similar how ms word allow users open documents opened else read only.
my class has boolean property determines if class should read-only, possible use property somehow dynamically add read-only attributes class properties @ run-time? if not alternative solution? should wrap class in read-only wrapper class?
immutability area c# still has room improve. while creating simple immutable types readonly
properties possible, once need more sophisticated control on when type mutable start running obstacles.
there 3 choices have, depending on how need "enforce" read-only behavior:
use read-only flag in type (like you're doing) , let caller responsible not attempting change properties on type - if write attempt made, throw exception.
create read-only interface , have type implement it. way can pass type via interface code should perform reads.
create wrapper class aggregates type , exposes read operations.
the first option easiest, in can require less refactoring of existing code, offers least opportunity author of type inform consumers when instance immutable vs when not. option offers least support compiler in detecting inappropriate use - , relegates error detection runtime.
the second option convenient, since implementing interface possible without refactoring effort. unfortunately, callers can still cast underlying type , attempt write against it. often, option combined read-only flag ensure immutability not violated.
the third option strongest, far enforcement goes, can result in duplication of code , more of refactoring effort. often, it's useful combine option 2 , 3, make relationship between read-only wrapper , mutable type polymorphic.
personally, tend perfer third option when writing new code expect need enforce immutability. fact it's impossible "cast-away" immutable wrapper, , allows avoid writing messy if-read-only-throw-exception checks every setter.
Comments
Post a Comment