In the below code, I would like to use the code in static load method to refresh the object… but how would I reset the current object with new object ? Is copying field by field is the only way ?
class WIP
{
// <Snipped> Various other properties...
public Boolean Refresh()
{
// Need to change the current object with the updated object
this = WIP.Load(this.ObjectID); // Says this is readonly...
return true;
}
public static WIP Load(long ObjectID)
{
// This static method fetches the data from DB and returns the object.
}
}
Edit : I just got this idea after posting the question… Are there any traps in this ?
class WIP
{
// <Snipped> Various other properties...
public Boolean Refresh()
{
// This method fetches the data from DB and updates the object.
}
public static WIP Load(long ObjectID)
{
WIP newObject = new WIP();
newObject.ObjectID = ObjectID;
newObject.Refresh();
return newObject;
}
}
No, you can’t. The closest you can come is basically to copy every member – which isn’t going to work if some are read-only, of course.
Either you’re trying to make your object immutable – in which case it shouldn’t change under the feet of code which already has a reference to your object – or you’re not, in which case you just need to make it fully mutable (ideally in some atomic fashion if there are multiple threads involved).