I have a use case that I’ve never really dealt with before. I have an object that after the user clicks “Save” should not be changed. Initially I created two objects, DraftObject and SavedObject. For the latter I created a constructor that only accepted the DraftObject and set each property as protected set.
This works but does not seem ideal. It seems like I should be able to set a property on my object that controls whether the other fields are editable. What’s the best way to do this? Forgive my pseudo-code, but this is what I was toying with:
public class MySpecialObject {
public virtual string MyProperty { get { return MyProperty; }
set {
if (State == "Locked")
{
return;
} else
{
MyProperty = MyProperty;
}
}
public virtual string State { get { return State; }
set {
if (State == "Locked")
{
return;
} else
{
State = State;
}
}
This seems ugly, especially if I have to do this to every single property in my class. There’s got to be a better way to do this, any ideas?
This is actually a fairly interesting issue, because there’s a lot to be said for objects that are either immutable, or that start off mutable but can be locked down to become immutable.
Addressing your question in specific, I think it may make more sense to throw an
InvalidOperationExceptionif there’s an attempt to set a locked property. I don’t know of any cleaner or better way.edit
In a parallel post, JLWarlow pointed out that this is exactly how
SecureStringworks when you callMakeReadOnly.